How to create a true singleton in java? - java

I am facing a problem with my singleton when used across multiple class loaders. E.g Singleton accessed by multiple EJBs. Is there any way to create a singleton which has only one instance across all class loader?
I am looking for pure java solution either using custom class loader or some other way.

The only way would be to make your singleton class be loaded by a single classloader - put that jar file in the bootclasspath, for example.
A static variable is inherently tied to the classloader which loaded the class containing that variable. It's just the way it works. If you need absolutely one instance, you need that class to only be loaded by one classloader.

JavaEE app servers generally solve this problem by setting up the singleton as a "service", the exact definition and configuration of which depends on the appserver in question.
For example, in JBoss you could use a xyz-service.xml descriptor to set up a singleton object that hangs off the JNDI or JMX tree, and your application components (e.g. your EJBs) would fetch the singleton from the tree. That protects you to some extent from the underlying classloader semantics.

J2EE is designed with clustering in mind, so any designs that it supports are going to have to work with multiple JVM's. I take it from your question that you aren't concerned about a clustered environment, so a simple insertion into JNDI on your app server should do it. In Glassfish, that is called a lifecycle listener. After the startup even, insert your singleton into JNDI, and then have everything else do a JNDI lookup to find it.
Note that GlassFish could still mess you up here, in that it could serialize the class to JNDI causing you to get different instances. I doubt it actually does this within one JVM, but you won't know until you try it.
The real bottom line answer is that J2EE is hostile to a global true singleton, and the J2EE way around the problem is to rethink the solution. Something like a database to hold values or some other external service that can ensure that only one instance of the data (even if multiple instances of objects representing the data) exists is the J2EE way.

To achieve TRUE Singleton, you have follow below guidelines:
Make your class as final. Others can't sub-class it and create one more instance
Make your Singleton instance as private static final
Provide private constructor and public getInstance() method.
Make sure that this Singleton class is loaded by one ClassLoader only
override readResolve() method and return same instance without creating new instance in de-Serialization process.
Sample code:
final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}
Refer to below SE question for more details:
What is an efficient way to implement a singleton pattern in Java?

Related

Java best way to share an object across other objects without using static

I have class A which instantiate class B which in turn do same for class C and so on, forming a large tree. I now need to instantiate an object that should be available all across the tree and I don't want to individually inject this object manually in all classes. I don't want to use a static because there could be different instances of class A running concurrently in different thread and this shared object must be unique per thread. I don't have much experience with thread safe operations.
Use Spring to manage the instance. That way you can inject your instance into any class that needs it and, provided the creation of the parent class is spring managed, the injected bean will be populated.
In some more detail, what you can do is define a class.
public class MyBean {
// Add your class details.
}
And ensure that Spring is either scanning its package or you have defined the bean in your applicationContext.xml file like this. The next stage is to inject this bean where you need to, using the #Autowired annotation..
#Autowired
private MyBean myBean;
And on the creation of that class, myBean will be populated with the same instance of MyBean that was initially created.
Advantages
Doing it this way means that your solution scales well. You can inject it anywhere without constantly changing constructors (and when you're creating more and more sub classes and relationships between classes, this is a prime candidate for Shotgun Surgery.
It's always good to learn about technologies that are used in industry.
Managing a single instance of a class using other methods (like the Singleton pattern) is usually a bad idea.
Disadvantages
Spring does a lot more than just inject objects, and you're pulling down a lot of classes to do just this, which will increase the size of your solution, although not significantly.
Extra Reading
Have a look at a basic Spring tutorial to get you going.
Have a look at the different scopes that you can create beans with, in case some of them suit your needs better.
You either need a local reference in the context that you want to use the object or you need a static reference. Since you don't want to use static you need to get a local reference. You can do this by passing the object in in the constructor or by adding a setter method. Then higher up the tree where ever you construct the child node you pass in the needed object.
You can have kind of a "Parallel Singleton" so to say, i.e. instead of having only one instance it will keep as many instances as there are threads, in a hashmap with a thread-related object being the key.

Singleton's other members

My question is broad, so I've split in two parts, and tried to be as specific as I can with what I know so far.
First part
A singleton holds a private static instance of itself. Some questions about singletons:
1. Should it's members also be static, or does that depend on the requirements?
2. If the answer to 1. is unequivocally yes, then what would be the point of having a private instance variable to begin with, if all members belong to the class?
3. Is the private instance needed because the JVM needs a referable object (THE singleton) to hold on to for the length of its (JVM's) life?
Second part
There is a requirement to make multiple concurrent remote calls within a tomcat hosted web application (the app utilizes GWT for some components, so I can utilize a servlet for this aforementioned requirement if a good solution requires this). Currently, I create an executor service with a cached thread pool into which I pass my callables (each callable containing an endpoint configuration), for each individual process flow that requires such calls. To me it would make sense if the thread pool was shared by multiple flows, instead of spawning pools of their own. Would a singleton holding a static thread pool be a good solution for this?
One note is that it is important to distinguish between the concept of a singleton (a class/object that has only a single instance) and the design pattern which achieves this via a class holding a single static instance of itself accessible in the global static name space. The concept of a singleton is frequently used in designs, the implementation of it via the singleton design pattern, however, is often frowned upon.
In the below, singleton is used to refer to the specific design pattern.
Part 1
A Singleton's members do not need to be static, and usually are not.
See 1.
A singleton (design pattern) requires an instance to itself in order to return that instance to users of the singleton, as well as keeping a reference to itself active to avoid garbage collection (as you suggest). Without this single instance, the object is essentially not an implementation of the singleton design pattern. You can create a class for which you only create a single instance and pass this class around where it is required (avoiding the global static namespace), and this would essentially be a recommended way to avoid using the singleton pattern.
Part 2:
Sharing your thread pools is probably wise (but depends on your requirements), and this can be done in a number of ways. One way would be to create a single pool and to pass this pool (inject it) into the classes that require it. Usual recommendation for this is to use something like Spring to handle this for you.
Using a singleton is also an option, but even if your thread pool here is encapsulated in a singleton, it is still generally preferable to inject this singleton (preferably referenced via an interface) into dependent objects (either via a setter or in their constructor) instead of having your objects refer to the singleton statically. There are various reasons for this, with testing, flexibility, and control over order of instantiation being some examples.
A Singleton's members need not be be static.
Invalidated by answer to point 1.
The instance of itself that the singleton need not be private either. You need an instance stored to a static member (public or private) if you have any other non-static member on the singleton. If there is any non-static member(it depends on your requirement) , then you need an instance to access that member(yes, JVM needs a referable object if the member is non-static)
Singleton member doesn't need to be static
Look at point 1
Singleton instance must be static (of course) and must be accessed by a static method; in addiction must have a private constructor to prevent new instance to be created
public class SingletonNumber10 {
public static SingletonNumber10 getInstance() {
if(null == instance) {
instance = new SingletonNumber10(10);
}
return instance;
}
private int number;
private static SingletonNumber10 instance;
private SingletonNumber10(int number) {
this.number = number;
}
public int getNumber() {
return this.number;
}
public static void main(String[] args) {
System.out.println(SingletonNumber10.getInstance());
System.out.println(SingletonNumber10.getInstance());
}
}
A singleton holds a private static instance of itself.
Not always, in fact, that's not even the best way to do it in Java.
public enum Director {
INSTANCE;
public int getFive() {
return 5;
}
}
Is a perfectly valid singleton, and is far more likely to remain the only copy in existence than a class that holds a private static instance of itself.
1. Should it's members also be static
No, the members should not be static, because then there is no need for a class, and therefore no need for that class to be a singleton. All static routines are subject to code maintenance issues, similar to C / C++ functions. Even though with singletons you won't have multiple instances to deal with, having the method off of an instance provides you with certain abilities to morph the code in the future.
2. If the answer to 1. is unequivocally yes.
It's not, so no need to answer #2.
3. Is the private instance needed because the JVM needs a
referable object (THE singleton) to hold on to for the
length of its (JVM's) life?
No, the private instance is needed because you have to have some ability to determine if the constructor was called previous to the access. This is typically done by checking to see if the instance variable is null. With race conditions and class loader considerations, it is incredibly difficult to make such code correct. Using the enum technique, you can ensure that there is only on instance, as the JVM internals are not subject to the same kinds of race conditions, and even if they were, only one instance is guaranteed to be presented to the program environment.
There is a requirement to make multiple concurrent remote calls within
a tomcat hosted web application (the app utilizes GWT for some components,
so I can utilize a servlet for this aforementioned requirement if a good
solution requires this). Currently, I create an executor service with a cached
thread pool into which I pass my callables (each callable containing an endpoint
configuration), for each individual process flow that requires such calls. To
me it would make sense if the thread pool was shared by multiple flows, instead
of spawning pools of their own. Would a singleton holding a static thread pool be
a good solution for this?
It depends. What are the threads in the pool going to be doing? If it's a thread to handle the task, eventually they will all get tied up with the long running tasks, possibly starving other critical processing. If you have a very large number of tasks to perform, perhaps restructuring the processing similar to the call-back patterns used in NIO might actually give you better performance (where one thread handles dispatching of call-backs for many tasks, without a pool).
Until you present a second way of handling the problem, or make more details of the operating environment available, the only solution presented is typically a good solution.
PS. Please don't expand on the details of the environment. The question submission process is easy, so if you want to expand on the second part, resubmit it as an independent question.

Singleton objects and Java servlets

When I access a singleton Java object from withing a servlet, that object is only "single" or "one instance" for the give servlet thread or single throughout the JVM on the Server OS (like Linux)?
I mean when client connects to the servlet/service, are singleton object are unique to each thread created for each client or its unique throughout the whole JVM installed in the machine?
I think the object is unique for each user, not to the whole JVM. The only persistent information is the one you put in the user session.
I'm not sure, but I think you can acomplish to have one instance of a Class in the whole Application Server using the ClassLoader class, however I don know how it's done.
UPDATE:
Taken from the Java Article "When is a Singleton not a Singleton?"
Multiple Singletons Simultaneously Loaded by Different Class Loaders
When two class loaders load a class, you actually have two copies of the class, and each one can have its own Singleton instance. That is particularly relevant in servlets running in certain servlet engines (iPlanet for example), where each servlet by default uses its own class loader. Two different servlets accessing a joint Singleton will, in fact, get two different objects.
Multiple class loaders occur more commonly than you might think. When browsers load classes from the network for use by applets, they use a separate class loader for each server address. Similarly, Jini and RMI systems may use a separate class loader for the different code bases from which they download class files. If your own system uses custom class loaders, all the same issues may arise.
If loaded by different class loaders, two classes with the same name, even the same package name, are treated as distinct -- even if, in fact, they are byte-for-byte the same class. The different class loaders represent different namespaces that distinguish classes (even though the classes' names are the same), so that the two MySingleton classes are in fact distinct. (See "Class Loaders as a Namespace Mechanism" in Resources.) Since two Singleton objects belong to two classes of the same name, it will appear at first glance that there are two Singleton objects of the same class.
I'd say it depends on how the singleton is implemented, but all requests for a given app execute in the same VM, so it should be one instance for all requests.
EDIT: This is assuming a straight-forward Singleton implementation similar to:
public class MySingleton {
private static MySingleton _instance;
// for sake of simplicity, I've left out handling of
// synchronization/multi-threading issues...
public static MySingleton getInstance() {
if (_instance == null) _instance = new MySingleton();
return _instance;
}
}
Yes it is Singleton. But the scope of the singleton depends on where the class is located.
If it is located inside application, it is singleton for that application. If the same class is present inside another application then another object is created for that application and it is singleton for that application.
If it is located outside application and within server, it is singleton for the VM.
According to this
https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html
every Web application has it's own class loader, so the singleton will be unique for one application and it can't be visible to another
When you create a Singleton instance, all request instances will share the same instance for the current class loader it uses.
Since all the Servlets run on a webserver which runs on a single JVM, there will be only a single Singelton Object for all your servlets.

How do I find where an instance of a Java singleton is created?

In a large, complex program it may not be simple to discover where in the
code a Singleton has been instantiated. What is the best approach to keep track of created singleton instances in order to re-use them?
Regards,
RR
A Singleton usually has a private constructor, thus the Singleton class is the only class which can instantiate the one and only singleton instance.
It's the responsibilty of singleton class developer to make sure that the instance is being reused on multiple calls.
As a user, you shouldn't worry about it.
class Singelton
{
private static Singelton _singelton = null;
private Singelton()
{
}
// NOT usable for Multithreaded program
public static Singelton CreateMe()
{
if(_singelton == null)
_singelton = new Singelton();
return _singelton;
}
}
Now, from anywhere in your code, you can instantiate Singelton, how many times you like and each time assign it to different reference. but c'tor is called ONLY once.
I would use an enum
enum Singleton {
INSTANCE:
}
or something similar which cannot be instantiated more than once and globally accessible.
General practice for naming methods which create/return singletons is getInstance(). I don't understand the situation when you can't find the place in code where singletons created, but you can search for this method name.
If you want to catch the exact moment of singleton creation - you can use AOP. AspectJ is a good example in java. You will be able to execute your code before/after creation of class or calling getInstance() method.
If your question is about reusing of created Singletons, then search this site. For example

Java Singleton Design Pattern : Questions

I had an interview recently and he asked me about Singleton Design Patterns about how are they implemented and I told him that using static variables and static methods we can implement Singleton Design Patterns.
He seems to be half satisfied with the answer but I want to know
How many different ways we can
implement Singleton Design Pattern
in Java ?
What is the scope of Singleton Object and how does it actually work inside JVM ? I know we would always have one instance of Singleton Object but what is the actual scope of that object, is it in JVM or if there are multiple application running than it's scope is per context basis inside the JVM, I was really stumped at this and was unable to give satisfying explanation ?
Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
Any inputs would be highly appreciated about Singleton and what are the main things to keep in mind while dealing with Singletons ?
Thanks.
There are a few ways to implement a Singleton pattern in Java:
// private constructor, public static instance
// usage: Blah.INSTANCE.someMethod();
public class Blah {
public static final Blah INSTANCE = new Blah();
private Blah() {
}
// public methods
}
// private constructor, public instance method
// usage: Woo.getInstance().someMethod();
public class Woo {
private static final Woo INSTANCE = new Woo();
private Woo() {
}
public static Woo getInstance() {
return INSTANCE;
}
// public methods
}
// Java5+ single element enumeration (preferred approach)
// usage: Zing.INSTANCE.someMethod();
public enum Zing {
INSTANCE;
// public methods
}
Given the examples above, you will have a single instance per classloader.
Regarding using a singleton in a cluster...I'm not sure what the definition of "using" is...is the interviewer implying that a single instance is created across the cluster? I'm not sure if that makes a whole lot of sense...?
Lastly, defining a non-singleton object in spring is done simply via the attribute singleton="false".
I disagree with #irreputable.
The scope of a Singleton is its node in the Classloader tree. Its containing classloader, and any child classloaders can see the Singleton.
It's important to understand this concept of scope, especially in the application servers which have intricate Classloader hierarchies.
For example, if you have a library in a jar file on the system classpath of an app server, and that library uses a Singleton, that Singleton is going to (likely) be the same for every "app" deployed in to the app server. That may or may not be a good thing (depends on the library).
Classloaders are, IMHO, one of the most important concepts in Java and the JVM, and Singletons play right in to that, so I think it is important for a Java programmer to "care".
I find it hard to believe that so many answers missed the best standard practice for singletons - using Enums - this will give you a singleton whose scope is the class loader which is good enough for most purposes.
public enum Singleton { ONE_AND_ONLY_ONE ; ... members and other junk ... }
As for singletons at higher levels - perhaps I am being silly - but my inclination would be to distribute the JVM itself (and restrict the class loaders). Then the enum would be adequate to the job .
Singleton is commonly implemented by having a static instance object (private SingletonType SingletonType.instance) that is lazily instantiated via a static SingletonType SingletonType.getInstance() method. There are many pitfalls to using singletons, so many, in fact, that many consider singleton to be a design anti-pattern. Given the questions about Spring, the interviewer probably was looking for an understanding not only of singletons but also their pitfalls as well as a workaround for these pitfalls known as dependency injection. You may find the video on the Google Guice page particularly helpful in understanding the pitfalls of singletons and how DI addresses this.
3: Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?
The first part of this question is hard to answer without a technological context. If the cluster platform includes the ability to make calls on remote objects as if they were local objects (e.g. as is possible with EJBs using RMI or IIOP under the hood) then yes it can be done. For example, the JVM resident singleton objects could be proxies for a cluster-wide singleton object, that was initially located / wired via JNDI or something. But cluster-wide singletons are a potential bottleneck because each call on one of the singleton proxies results in an (expensive) RPC to a single remote object.
The second part of the question is that Spring Bean Factories can be configured with different scopes. The default is for singletons (scoped at the webapp level), but they can also be session or request scoped, or an application can define its own scoping mechanism.
a static field can have multiple occurrences in one JVM - by using difference class loaders, the same class can be loaded and initialized multiple times, but each lives in isolation and JVM treat the result loaded classes as completely different classes.
I don't think a Java programmer should care, unless he's writing some frameworks. "One per VM" is a good enough answer. People often talk that way while strictly speaking they are saying "one per classloader".
Can we have one singleton per cluster? Well that's a game of concepts. I would not appreciate an interviewer word it that way.
There's the standard way, which you already covered. Also, most dependency-injection schemes have some way to mark a class as a singleton; this way, the class looks just like any other, but the framework makes sure that when you inject instances of that class, it's always the same instance.
That's where it gets hairy. For example, if the class is initialized inside a Tomcat application context, then the singleton instance's lifetime is bound to that context. But it can be hard to predict where your classes will be initialized; so it's best not to make any assumptions. If you want to absolutely make sure that there's exactly one instance per context, you should bind it as an attribute of the ServletContext. (Or let a dependency-injection framework take care of it.)
--
Not sure I understand the question - but if you're talking about having a singleton instance that's shared between several cluster nodes, then I think EJB makes this possible (by way of remote beans), though I've never tried it. No idea how Spring does it.
Singleton is a creational pattern and hence governs object instantiation. Creating singletons would mandate that you voluntarily or involuntarily give up control on creating the object and instead rely on some way of obtaining access to it.
This can be achieved using static methods or by dependency injection or using the factory pattern. The means is immaterial. In case of the normal protected constructor() approach, the consumer perforce needs to use the static method for accessing the singleton. In case of DI, the consumer voluntarily gives up control over the instantiation of the class and instead relies on a DI framework to inject the instance into itself.
As pointed out by other posters, the class loader in java would define the scope of the singleton. Singletons in clusters are usually "not single instances" but a collection of instances that exhibit similar behavior. These can be components in SOA.
The Following Code is from here
The Key point is you should Override the clone method...The Wikipedia example also is helpful.
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}
public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}
private static SingletonObject ref;
}
Query 1:
Different ways of creating Singleton
Normal Singleton : static initialization
ENUM
Lazy Singleton : Double locking Singleton & : Initialization-on-demand_holder_idiom singleton
Have a look at below code:
public final class Singleton{
private static final Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
public enum EnumSingleton {
INSTANCE;
}
public static void main(String args[]){
System.out.println("Singleton:"+Singleton.getInstance());
System.out.println("Enum.."+EnumSingleton.INSTANCE);
System.out.println("Lazy.."+LazySingleton.getInstance());
}
}
final class LazySingleton {
private LazySingleton() {}
public static LazySingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazySingleton INSTANCE = new LazySingleton();
}
}
Related SE questions:
What is an efficient way to implement a singleton pattern in Java?
Query 2:
One Singleton instance is created per ClassLoader. If you want to avoid creation of Singleton object during Serializaiton, override below method and return same instance.
private Object readResolve() {
return instance;
}
Query 3:
To achieve a cluster level Singleton among multiple servers, store this Singleton object in a distributed caches like Terracotta, Coherence etc.
Singleton is a creational design pattern.
Intents of Singleton Design Pattern :
Ensure a class has only one instance, and provide a global point of
access to it.
Encapsulated "just-in-time initialization" or "initialization on
first use".
I'm showing three types of implementation here.
Just in time initialization (Allocates memory during the first run, even if you don't use it)
class Foo{
// Initialized in first run
private static Foo INSTANCE = new Foo();
/**
* Private constructor prevents instantiation from outside
*/
private Foo() {}
public static Foo getInstance(){
return INSTANCE;
}
}
Initialization on first use (or Lazy initialization)
class Bar{
private static Bar instance;
/**
* Private constructor prevents instantiation from outside
*/
private Bar() {}
public static Bar getInstance(){
if (instance == null){
// initialized in first call of getInstance()
instance = new Bar();
}
return instance;
}
}
This is another style of Lazy initialization but the advantage is, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized). Read More at SourceMaking.com
class Blaa{
/**
* Private constructor prevents instantiation from outside
*/
private Blaa() {}
/**
* BlaaHolder is loaded on the first execution of Blaa.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class BlaaHolder{
public static Blaa INSTANCE = new Blaa();
}
public static Blaa getInstance(){
return BlaaHolder.INSTANCE;
}
}

Categories