ThreadLocal with Singletons - java

I am working on the following piece of code. Two threads requiring their own instance of a singleton. Thread Local is an obvious solution to this. However I am still facing issues running the threads with their own local copy. I have an example of the scenario in a couple of java classes.
public class Singleton1 {
private int i = 0;
private static Singleton1 instance;
private Singleton1() {
}
public static final Singleton1 getInstance() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}
public int increment() {
return i++;
}
}
public class Holder1 {
private final Singleton1 instance;
public Holder1() {
ThreadLocalSingleton1 singleton1 = new ThreadLocalSingleton1();
instance = singleton1.get();
}
public int increment() {
return instance.increment();
}
private class ThreadLocalSingleton1 extends ThreadLocal<Singleton1> {
#Override
protected Singleton1 initialValue() {
return Singleton1.getInstance();
}
}
}
public class HolderTest {
/**
* #param args
*/
public static void main(String[] args) {
HolderTest test = new HolderTest();
HolderThread thread1 = test.getHolderThread("thread1");
HolderThread thread2 = test.getHolderThread("thread2");
thread1.run();
thread2.run();
}
public HolderThread getHolderThread(String name) {
return new HolderThread(name);
}
private class HolderThread implements Runnable {
String name;
Holder1 holder1 = new Holder1();
public HolderThread(String name) {
this.name = name;
}
#Override
public void run() {
while (true) {
System.out.println(name + " " + holder1.increment());
}
}
}
When the ThreadLocal wrappers call getInstance on the Singleton classes I do not get a new instance each time? How do I make this work for my purposes?
The code above is a simple version of the actual code I am working with. I have Singleton classes which I cannot change from being singletons. I am creating a test client which needs to run as a single process but with many threads. Each of these threads needs to have its own instance of these singletons.

Your target class shall not be singleton, but you must access it just using the ThreadLocal, and creating a new instance if ThreadLocal instance is empty (doesn't hold a reference to an instance of your target object).
Another solution is to make your Target class singleton, and hold its state in ThreadLocal variables.

You seem to be painted into a corner.
On the one hand, you have an existing codebase that you need to test and that code uses (genuine, properly implemented) singleton objects. In particular, the declaration of the Singleton1() constructor as private in your examplar class Singleton1 makes it impossible to declare a subclass.
On the other hand, your testing requires you to write a client with lots of these Singleton1 instances.
On the face of it, that is impossible. There is no way to make two instances of the Singleton1 class in the JVM, and there is no way to declare a (compilable / loadable) subclass of Singleton1.
This is per design; i.e. it is what the designer of the Singleton1 class intended. (And if not, then the answer is to change Singleton1 to make it easier to test. For example, by making the Singleton1 constructor not private so that multiple instances can be created for test purposes. )
(For instance, your current attempt at implementing ThreadLocalSingleton1 fails because the Singleton1.getInstance() returns the global instance of Singleton1. No matter what you do, there is no way to create any other instance of the Singleton1 class.)
However, I can think of two workarounds for your particular use-case.
I am writing a test client which needs to run as as single java process. The test client is used for load testing will have X threads accessing a server using a core project (that I cannot change too much) which has many singletons. The singletons hold state which will be required per thread.
Here are the workarounds:
Instead of running one JVM with N instances of your test thread, run N separate JVMs each with a single test thread. Each JVM / test thread can have its own instance of Singleton.
Have each of your test threads create a new classloader, and use that classloader to dynamic load the Singleton1 class and everything with a direct or indirect static dependency on the Singleton1 type. The idea is for each classloader to load its own copy of the Singleton1 class. Since each copy will be a distinct type1, it will have its own private static Singleton1 instance variable.
Note that these workarounds do provide not "thread-local" instances of your Singleton1 class. That is both technically impossible ... and a contradiction of the definition of singleton.
In both cases you have true singleton instances, but they are instances of different Singleton1 types ... for different reasons.
1 - At runtime, the type of a class instance is conceptually a pair consisting of the fully qualified name of the class and the identity of the classloader that loaded the class. If the same bytecode file is loaded by different classloaders, then you get different runtime types.

Do you mean something like this?
private static final ThreadLocal<AtomicInteger> COUNTER = new ThreadLocal<AtomicInteger>() {
#Override
protected AtomicInteger initialValue() {
return new AtomicInteger();
}
};
public static int incrementAndGet() {
return COUNTER.get().incrementAndGet();
}

Please, take a look at the ThreadLocal working example below:
public class YourDataHolder {
private static ThreadLocal dataVariable = new ThreadLocal();
private static YourDataHolder dataHolderVar;
private YourDataHolder() { }
public void storeDataToThreadLocal (String userName) {
dataVariable.set(userName);
}
public String readDataFromThreadLocal () {
if (dataVariable.get() != null) {
return (String) dataVariable.get();
}
}
public static ServiceVersionHolder getInstance () {
if (dataHolderVar == null) {
dataHolderVar = new YourDataHolder();
}
return dataHolderVar;
}
}

Use synchronized for multithreading.
public static synchronized final Singleton getInstance() {
This way the threads will "lock" the method: only one thread will be allowed to enter the method at a time, other threads will block until the method is unlocked (the thread executing it leaves). You won't have those concurrency issues.
Also you don't need 2 singletons (which IMHO actually makes no sense and defeats the very own purpose of a singleton...).

Related

Can anyone help me with the Singleton in java [duplicate]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
What is an efficient way to implement a singleton design pattern in Java?
Use an enum:
public enum Foo {
INSTANCE;
}
Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video. Also see slides 30-32 of his presentation (effective_java_reloaded.pdf):
The Right Way to Implement a Serializable Singleton
public enum Elvis {
INSTANCE;
private final String[] favoriteSongs =
{ "Hound Dog", "Heartbreak Hotel" };
public void printFavorites() {
System.out.println(Arrays.toString(favoriteSongs));
}
}
Edit: An online portion of "Effective Java" says:
"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."
Depending on the usage, there are several "correct" answers.
Since Java 5, the best way to do it is to use an enum:
public enum Foo {
INSTANCE;
}
Pre Java 5, the most simple case is:
public final class Foo {
private static final Foo INSTANCE = new Foo();
private Foo() {
if (INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return INSTANCE;
}
public Object clone() throws CloneNotSupportedException{
throw new CloneNotSupportedException("Cannot clone instance of this class");
}
}
Let's go over the code. First, you want the class to be final. In this case, I've used the final keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a private static final Foo field to hold the only instance, and a public static Foo getInstance() method to return it. The Java specification makes sure that the constructor is only called when the class is first used.
When you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.
You can use a private static class to load the instance. The code would then look like:
public final class Foo {
private static class FooLoader {
private static final Foo INSTANCE = new Foo();
}
private Foo() {
if (FooLoader.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return FooLoader.INSTANCE;
}
}
Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.
When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.
public final class Foo implements Serializable {
private static final long serialVersionUID = 1L;
private static class FooLoader {
private static final Foo INSTANCE = new Foo();
}
private Foo() {
if (FooLoader.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return FooLoader.INSTANCE;
}
#SuppressWarnings("unused")
private Foo readResolve() {
return FooLoader.INSTANCE;
}
}
The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.
Disclaimer: I have just summarized all of the awesome answers and wrote it in my own words.
While implementing Singleton we have two options:
Lazy loading
Early loading
Lazy loading adds bit overhead (lots of to be honest), so use it only when you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization. Otherwise, choosing early loading is a good choice.
The most simple way of implementing a singleton is:
public class Foo {
// It will be our sole hero
private static final Foo INSTANCE = new Foo();
private Foo() {
if (INSTANCE != null) {
// SHOUT
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return INSTANCE;
}
}
Everything is good except it's an early loaded singleton. Lets try lazy loaded singleton
class Foo {
// Our now_null_but_going_to_be sole hero
private static Foo INSTANCE = null;
private Foo() {
if (INSTANCE != null) {
// SHOUT
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
// Creating only when required.
if (INSTANCE == null) {
INSTANCE = new Foo();
}
return INSTANCE;
}
}
So far so good, but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero.
So let’s protect it from evil multi threading:
class Foo {
private static Foo INSTANCE = null;
// TODO Add private shouting constructor
public static Foo getInstance() {
// No more tension of threads
synchronized (Foo.class) {
if (INSTANCE == null) {
INSTANCE = new Foo();
}
}
return INSTANCE;
}
}
But it is not enough to protect out hero, really!!! This is the best we can/should do to help our hero:
class Foo {
// Pay attention to volatile
private static volatile Foo INSTANCE = null;
// TODO Add private shouting constructor
public static Foo getInstance() {
if (INSTANCE == null) { // Check 1
synchronized (Foo.class) {
if (INSTANCE == null) { // Check 2
INSTANCE = new Foo();
}
}
}
return INSTANCE;
}
}
This is called the "double-checked locking idiom". It's easy to forget the volatile statement and difficult to understand why it is necessary.
For details: The "Double-Checked Locking is Broken" Declaration
Now we are sure about evil threads, but what about the cruel serialization? We have to make sure even while de-serialiaztion no new object is created:
class Foo implements Serializable {
private static final long serialVersionUID = 1L;
private static volatile Foo INSTANCE = null;
// The rest of the things are same as above
// No more fear of serialization
#SuppressWarnings("unused")
private Object readResolve() {
return INSTANCE;
}
}
The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.
Finally, we have added enough protection against threads and serialization, but our code is looking bulky and ugly. Let’s give our hero a makeover:
public final class Foo implements Serializable {
private static final long serialVersionUID = 1L;
// Wrapped in a inner static class so that loaded only when required
private static class FooLoader {
// And no more fear of threads
private static final Foo INSTANCE = new Foo();
}
// TODO add private shouting construcor
public static Foo getInstance() {
return FooLoader.INSTANCE;
}
// Damn you serialization
#SuppressWarnings("unused")
private Foo readResolve() {
return FooLoader.INSTANCE;
}
}
Yes, this is our very same hero :)
Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread-safe.
And we have come so far. Here is the best way to achieve everything we did is best possible way:
public enum Foo {
INSTANCE;
}
Which internally will be treated like
public class Foo {
// It will be our sole hero
private static final Foo INSTANCE = new Foo();
}
That's it! No more fear of serialization, threads and ugly code. Also ENUMS singleton are lazily initialized.
This approach is functionally equivalent to the public field approach,
except that it is more concise, provides the serialization machinery
for free, and provides an ironclad guarantee against multiple
instantiation, even in the face of sophisticated serialization or
reflection attacks. While this approach has yet to be widely adopted,
a single-element enum type is the best way to implement a singleton.
-Joshua Bloch in "Effective Java"
Now you might have realized why ENUMS are considered as best way to implement a singleton and thanks for your patience :)
Updated it on my blog.
The solution posted by Stu Thompson is valid in Java 5.0 and later. But I would prefer not to use it because I think it is error prone.
It's easy to forget the volatile statement and difficult to understand why it is necessary. Without the volatile this code would not be thread safe any more due to the double-checked locking antipattern. See more about this in paragraph 16.2.4 of Java Concurrency in Practice. In short: This pattern (prior to Java 5.0 or without the volatile statement) could return a reference to the Bar object that is (still) in an incorrect state.
This pattern was invented for performance optimization. But this is really not a real concern any more. The following lazy initialization code is fast and - more importantly - easier to read.
class Bar {
private static class BarHolder {
public static Bar bar = new Bar();
}
public static Bar getBar() {
return BarHolder.bar;
}
}
Thread safe in Java 5+:
class Foo {
private static volatile Bar bar = null;
public static Bar getBar() {
if (bar == null) {
synchronized(Foo.class) {
if (bar == null)
bar = new Bar();
}
}
return bar;
}
}
Pay attention to the volatile modifier here. :) It is important because without it, other threads are not guaranteed by the JMM (Java Memory Model) to see changes to its value. The synchronization does not take care of that--it only serializes access to that block of code.
#Bno's answer details the approach recommended by Bill Pugh (FindBugs) and is arguable better. Go read and vote up his answer too.
Forget lazy initialization; it's too problematic. This is the simplest solution:
public class A {
private static final A INSTANCE = new A();
private A() {}
public static A getInstance() {
return INSTANCE;
}
}
Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments against it.
There's nothing inherently wrong with it I suppose, but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I've found dependency injection (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.
I'm mystified by some of the answers that suggest dependency injection (DI) as an alternative to using singletons; these are unrelated concepts. You can use DI to inject either singleton or non-singleton (e.g., per-thread) instances. At least this is true if you use Spring 2.x, I can't speak for other DI frameworks.
So my answer to the OP would be (in all but the most trivial sample code) to:
Use a DI framework like Spring Framework, then
Make it part of your DI configuration whether your dependencies are singletons, request scoped, session scoped, or whatever.
This approach gives you a nice decoupled (and therefore flexible and testable) architecture where whether to use a singleton is an easily reversible implementation detail (provided any singletons you use are threadsafe, of course).
Really consider why you need a singleton before writing it. There is a quasi-religious debate about using them which you can quite easily stumble over if you google singletons in Java.
Personally, I try to avoid singletons as often as possible for many reasons, again most of which can be found by googling singletons. I feel that quite often singletons are abused because they're easy to understand by everybody. They're used as a mechanism for getting "global" data into an OO design and they are used because it is easy to circumvent object lifecycle management (or really thinking about how you can do A from inside B). Look at things like inversion of control (IoC) or dependency injection (DI) for a nice middle ground.
If you really need one then Wikipedia has a good example of a proper implementation of a singleton.
Following are three different approaches
Enum
/**
* Singleton pattern example using Java Enum
*/
public enum EasySingleton {
INSTANCE;
}
Double checked locking / lazy loading
/**
* Singleton pattern example with Double checked Locking
*/
public class DoubleCheckedLockingSingleton {
private static volatile DoubleCheckedLockingSingleton INSTANCE;
private DoubleCheckedLockingSingleton() {}
public static DoubleCheckedLockingSingleton getInstance() {
if(INSTANCE == null) {
synchronized(DoubleCheckedLockingSingleton.class) {
// Double checking Singleton instance
if(INSTANCE == null) {
INSTANCE = new DoubleCheckedLockingSingleton();
}
}
}
return INSTANCE;
}
}
Static factory method
/**
* Singleton pattern example with static factory method
*/
public class Singleton {
// Initialized during class loading
private static final Singleton INSTANCE = new Singleton();
// To prevent creating another instance of 'Singleton'
private Singleton() {}
public static Singleton getSingleton() {
return INSTANCE;
}
}
There is a lot of nuance around implementing a singleton. The holder pattern can not be used in many situations. And IMO when using a volatile - you should also use a local variable. Let's start at the beginning and iterate on the problem. You'll see what I mean.
The first attempt might look something like this:
public class MySingleton {
private static MySingleton INSTANCE;
public static MySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new MySingleton();
}
return INSTANCE;
}
...
}
Here we have the MySingleton class which has a private static member called INSTANCE, and a public static method called getInstance(). The first time getInstance() is called, the INSTANCE member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the INSTANCE variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().
But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the INSTANCE member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the INSTANCE member.
private static MySingleton INSTANCE;
public static synchronized MySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new MySingleton();
}
return INSTANCE;
}
Here we’ve used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance; it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of INSTANCE. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.
private static MySingleton INSTANCE;
public static MySingleton getInstance() {
if (INSTANCE == null) {
synchronize(MySingleton.class) {
INSTANCE = new MySingleton();
}
}
return INSTANCE;
}
Here we’ve moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we’ve also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the INSTANCE member as null.
They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.
private static MySingleton INSTANCE;
public static MySingleton getInstance() {
if (INSTANCE == null) {
synchronized(MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = createInstance();
}
}
}
return INSTANCE;
}
Here we issue another check from inside the block. If the INSTANCE member has already been set, we’ll skip initialization. This is called double-checked locking.
This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not “see” that the INSTANCE member has been updated. This is because of how Java optimizes memory operations.
Threads copy the original values of variables from main memory into the CPU’s cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread — being processed by a different CPU or core, using a different cache — will not see the changes made by the first. This will cause the second thread to see the INSTANCE member as null forcing a new instance of our singleton to be created.
private static volatile MySingleton INSTANCE;
public static MySingleton getInstance() {
if (INSTANCE == null) {
synchronized(MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = createInstance();
}
}
}
return INSTANCE;
}
We solve this by using the volatile keyword on the declaration of the INSTANCE member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.
But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile INSTANCE member — which we do four times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.
private static volatile MySingleton INSTANCE;
public static MySingleton getInstance() {
MySingleton result = INSTANCE;
if (result == null) {
synchronized(MySingleton.class) {
result = INSTANCE;
if (result == null) {
INSTANCE = result = createInstance();
}
}
}
return result;
}
Since the performance hit is due to operating directly on the volatile member, let’s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occurred while we were waiting for the lock.
I wrote an article about this recently. Deconstructing The Singleton. You can find more information on these examples and an example of the "holder" pattern there. There is also a real-world example showcasing the double-checked volatile approach.
I use the Spring Framework to manage my singletons.
It doesn't enforce the "singleton-ness" of the class (which you can't really do anyway if there are multiple class loaders involved), but it provides a really easy way to build and configure different factories for creating different types of objects.
Wikipedia has some examples of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).
Version 1:
public class MySingleton {
private static MySingleton instance = null;
private MySingleton() {}
public static synchronized MySingleton getInstance() {
if(instance == null) {
instance = new MySingleton();
}
return instance;
}
}
Lazy loading, thread safe with blocking, low performance because of synchronized.
Version 2:
public class MySingleton {
private MySingleton() {}
private static class MySingletonHolder {
public final static MySingleton instance = new MySingleton();
}
public static MySingleton getInstance() {
return MySingletonHolder.instance;
}
}
Lazy loading, thread safe with non-blocking, high performance.
If you do not need lazy loading then simply try:
public class Singleton {
private final static Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() { return Singleton.INSTANCE; }
protected Object clone() {
throw new CloneNotSupportedException();
}
}
If you want lazy loading and you want your singleton to be thread-safe, try the double-checking pattern:
public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if(null == instance) {
synchronized(Singleton.class) {
if(null == instance) {
instance = new Singleton();
}
}
}
return instance;
}
protected Object clone() {
throw new CloneNotSupportedException();
}
}
As the double checking pattern is not guaranteed to work (due to some issue with compilers, I don't know anything more about that), you could also try to synchronize the whole getInstance-method or create a registry for all your singletons.
I would say an enum singleton.
Singleton using an enum in Java is generally a way to declare an enum singleton. An enum singleton may contain instance variables and instance methods. For simplicity's sake, also note that if you are using any instance method then you need to ensure thread safety of that method if at all it affects the state of object.
The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.
/**
* Singleton pattern example using a Java Enum
*/
public enum Singleton {
INSTANCE;
public void execute (String arg) {
// Perform operation here
}
}
You can access it by Singleton.INSTANCE, and it is much easier than calling the getInstance() method on Singleton.
1.12 Serialization of Enum Constants
Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form. To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.lang.Enum.valueOf method, passing the constant's enum type along with the received constant name as arguments. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream.
The process by which enum constants are serialized cannot be customized: any class-specific writeObject, readObject, readObjectNoData, writeReplace, and readResolve methods defined by enum types are ignored during serialization and deserialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored--all enum types have a fixed serialVersionUID of 0L. Documenting serializable fields and data for enum types is unnecessary, since there is no variation in the type of data sent.
Quoted from Oracle documentation
Another problem with conventional Singletons are that once you implement the Serializable interface, they no longer remain singleton because the readObject() method always return a new instance, like a constructor in Java. This can be avoided by using readResolve() and discarding the newly created instance by replacing with a singleton like below:
// readResolve to prevent another instance of Singleton
private Object readResolve(){
return INSTANCE;
}
This can become even more complex if your singleton class maintains state, as you need to make them transient, but with in an enum singleton, serialization is guaranteed by the JVM.
Good Read
Singleton Pattern
Enums, Singletons and Deserialization
Double-checked locking and the Singleton pattern
There are four ways to create a singleton in Java.
Eager initialization singleton
public class Test {
private static final Test test = new Test();
private Test() {
}
public static Test getTest() {
return test;
}
}
Lazy initialization singleton (thread safe)
public class Test {
private static volatile Test test;
private Test() {
}
public static Test getTest() {
if(test == null) {
synchronized(Test.class) {
if(test == null) {
test = new Test();
}
}
}
return test;
}
}
Bill Pugh singleton with holder pattern (preferably the best one)
public class Test {
private Test() {
}
private static class TestHolder {
private static final Test test = new Test();
}
public static Test getInstance() {
return TestHolder.test;
}
}
Enum singleton
public enum MySingleton {
INSTANCE;
private MySingleton() {
System.out.println("Here");
}
}
This is how to implement a simple singleton:
public class Singleton {
// It must be static and final to prevent later modification
private static final Singleton INSTANCE = new Singleton();
/** The constructor must be private to prevent external instantiation */
private Singleton(){}
/** The public static method allowing to get the instance */
public static Singleton getInstance() {
return INSTANCE;
}
}
This is how to properly lazy create your singleton:
public class Singleton {
// The constructor must be private to prevent external instantiation
private Singleton(){}
/** The public static method allowing to get the instance */
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
/**
* The static inner class responsible for creating your instance only on demand,
* because the static fields of a class are only initialized when the class
* is explicitly called and a class initialization is synchronized such that only
* one thread can perform it, this rule is also applicable to inner static class
* So here INSTANCE will be created only when SingletonHolder.INSTANCE
* will be called
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
}
You need the double-checking idiom if you need to load the instance variable of a class lazily. If you need to load a static variable or a singleton lazily, you need the initialization on demand holder idiom.
In addition, if the singleton needs to be serializable, all other fields need to be transient and readResolve() method needs to be implemented in order to maintain the singleton object invariant. Otherwise, each time the object is deserialized, a new instance of the object will be created. What readResolve() does is replace the new object read by readObject(), which forced that new object to be garbage collected as there is no variable referring to it.
public static final INSTANCE == ....
private Object readResolve() {
return INSTANCE; // Original singleton instance.
}
Various ways to make a singleton object:
As per Joshua Bloch - Enum would be the best.
You can use double check locking also.
Even an inner static class can be used.
Enum singleton
The simplest way to implement a singleton that is thread-safe is using an Enum:
public enum SingletonEnum {
INSTANCE;
public void doSomething(){
System.out.println("This is a singleton");
}
}
This code works since the introduction of Enum in Java 1.5
Double checked locking
If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.
public class Singleton {
private static volatile Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class){
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.
Early loading singleton (works even before Java 1.5)
This implementation instantiates the singleton when the class is loaded and provides thread safety.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
public void doSomething(){
System.out.println("This is a singleton");
}
}
For JSE 5.0 and above, take the Enum approach. Otherwise, use the static singleton holder approach ((a lazy loading approach described by Bill Pugh). The latter solution is also thread-safe without requiring special language constructs (i.e., volatile or synchronized).
Another argument often used against singletons is their testability problems. Singletons are not easily mockable for testing purposes. If this turns out to be a problem, I like to make the following slight modification:
public class SingletonImpl {
private static SingletonImpl instance;
public static SingletonImpl getInstance() {
if (instance == null) {
instance = new SingletonImpl();
}
return instance;
}
public static void setInstance(SingletonImpl impl) {
instance = impl;
}
public void a() {
System.out.println("Default Method");
}
}
The added setInstance method allows setting a mockup implementation of the singleton class during testing:
public class SingletonMock extends SingletonImpl {
#Override
public void a() {
System.out.println("Mock Method");
}
}
This also works with early initialization approaches:
public class SingletonImpl {
private static final SingletonImpl instance = new SingletonImpl();
private static SingletonImpl alt;
public static void setInstance(SingletonImpl inst) {
alt = inst;
}
public static SingletonImpl getInstance() {
if (alt != null) {
return alt;
}
return instance;
}
public void a() {
System.out.println("Default Method");
}
}
public class SingletonMock extends SingletonImpl {
#Override
public void a() {
System.out.println("Mock Method");
}
}
This has the drawback of exposing this functionality to the normal application too. Other developers working on that code could be tempted to use the ´setInstance´ method to alter a specific function and thus changing the whole application behaviour, and therefore this method should contain at least a good warning in its javadoc.
Still, for the possibility of mockup-testing (when needed), this code exposure may be an acceptable price to pay.
Simplest singleton class:
public class Singleton {
private static Singleton singleInstance = new Singleton();
private Singleton() {}
public static Singleton getSingleInstance() {
return singleInstance;
}
}
Have a look at this post.
Examples of GoF Design Patterns in Java's core libraries
From the best answer's "Singleton" section,
Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)
java.lang.Runtime#getRuntime()
java.awt.Desktop#getDesktop()
java.lang.System#getSecurityManager()
You can also learn the example of Singleton from Java native classes themselves.
The best singleton pattern I've ever seen uses the Supplier interface.
It's generic and reusable
It supports lazy initialization
It's only synchronized until it has been initialized, then the blocking supplier is replaced with a non-blocking supplier.
See below:
public class Singleton<T> implements Supplier<T> {
private boolean initialized;
private Supplier<T> singletonSupplier;
public Singleton(T singletonValue) {
this.singletonSupplier = () -> singletonValue;
}
public Singleton(Supplier<T> supplier) {
this.singletonSupplier = () -> {
// The initial supplier is temporary; it will be replaced after initialization
synchronized (supplier) {
if (!initialized) {
T singletonValue = supplier.get();
// Now that the singleton value has been initialized,
// replace the blocking supplier with a non-blocking supplier
singletonSupplier = () -> singletonValue;
initialized = true;
}
return singletonSupplier.get();
}
};
}
#Override
public T get() {
return singletonSupplier.get();
}
}
I still think after Java 1.5, enum is the best available singleton implementation available as it also ensures that, even in the multi threaded environments, only one instance is created.
public enum Singleton {
INSTANCE;
}
And you are done!
Sometimes a simple "static Foo foo = new Foo();" is not enough. Just think of some basic data insertion you want to do.
On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution is
public class Singleton {
private static Singleton instance = null;
static {
instance = new Singleton();
// do some of your instantiation stuff here
}
private Singleton() {
if(instance!=null) {
throw new ErrorYouWant("Singleton double-instantiation, should never happen!");
}
}
public static getSingleton() {
return instance;
}
}
Now what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the static { } - block. that's the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
if (INSTANCE != null)
throw new IllegalStateException(“Already instantiated...”);
}
public synchronized static Singleton getInstance() {
return INSTANCE;
}
}
As we have added the Synchronized keyword before getInstance, we have avoided the race condition in the case when two threads call the getInstance at the same time.

What does reference return when object is being created in singleton pattern

Following is double-check implementation of singleton pattern. Thread A is executing line test=new Test(); But just at the same time, thread B first checks the value of test. What's the value of test as for thread B?
class Test {
private Test test;
private Test() {
}
public static Test get() {
if (test == null) { // Thread B. When object is being created,
// what's value of test. Is it always null before
// Thread B new object?
synchronized (test.getClass()) {
if (test == null) {
test = new Test(); // Thread A. This thread is creating object.
}
}
}
return test;
}
}
Added
If it's not a right version of singleton pattern, can volatile keyword solve the problem? That is, private volatile Test test;
It is unknown. That is why this implementation is considered wrong.
There is possibility that test = new Test() first create object then assign reference to it to test and only then initialize it.
So thread B will have reference to object, but it may be not initialized.
This one also seems to be a good approach as suggested by Bill Pugh to eliminate the drawbacks of double check locking (as mentioned in the question) and we don't need to do eager initialization as well to eliminate this :
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
Notice the private inner static class that contains the instance of the singleton class. When the singleton class is loaded, SingletonHelper class is not loaded into memory and only when someone calls the getInstance method, this class gets loaded and creates the Singleton class instance.
This is one of the most widely used approach for Singleton class as it doesn’t require synchronization.
If it's not a right version of singleton pattern, can volatile keyword
solve the problem?
Indeed, this :
private Test test;
should be declared :
private volatile Test test;
Otherwise the memory of the thread B may keep a stale version of test that may be null while the thread A valued it with the private constructor.
By specifying test as volatile, you ensure that any assignment on it performed by one thread will be visible by other threads.
Now this way of implementing a singleton is not very straight (double conditional statement plus explicit synchronization).
As two fine alternatives, you could use the enum singleton idiom :
public enum Test implements TestInterface{
SINGLETON;
...
}
Note that the interface is advised to write a naturally testable implementation and to be able to switch to other implementations.
or else the Bill Pugh singleton idiom (here is in the eager flavor) :
public class Test{
// executed as soon as the T class is loaded by the classLoader
private static Test instance = new Test();
private Test() {
}
public static TestgetInstance() {
return instance;
}
}

singleton public static final

I've been wondering about singletons in Java. By convention, a singleton is set up something like this:
private static MyClass instance = null;
public static MyClass getInstance(){
if (instance == null){
instance = new MyClass();
}
return instance;
}
private MyClass(){}
Recently I've switched to using the following:
public static final MyClass instance = new MyClass();
private MyClass(){}
This is a lot shorter, faster as there's no null-check, and typing MyClass.instance feels nicer to me than typing MyClass.getInstance(). Is there any reason why the second is not the mainstream way to do this?
The first version creates the instance the first time it is actually needed, while the second (the shorter) runs the constructor as soon as the class is initialized
A class or interface type T will be initialized immediately before the
first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant
variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10)
lexically nested within T (§8.1.3) is executed. [...]
Invocation of certain reflective methods in class Class and in
package java.lang.reflect also causes class or interface initialization.
The initialization upon first usage is a performance improvement that may speed up the startup of the application if the code in the constructor makes expensive operations. On the other hand, the second version is straightforward to read and is automatically thread-safe.
Anyway, the state of the art is not creating singleton in either ways: for a bunch of KB you can get dependency injection libraries that make it working for you, and also handle more complex scenarios (for example look at Spring and AOP-backed injection).
Note: the first version is not thread safe in the pasted snippet
The way you have first described is known as lazy instantiation, i.e the object will only be created when it is first called. This method is not thread-safe as it is possible for a second thread to create a second instance.
If you read the following book:
Effective Java by Joshua Bloch
He explains that the best implementation of the singleton pattern is through the use of an Enum :
public enum Singleton {
INSTANCE;
public void doSomething() {
...
}
}
Then you would call your singleton through the Enum as follows:
public class Test {
public void test(){
Singleton.INSTANCE.doSomething();
}
}
This fits nicely with what you are saying in terms of it looks nicer and shorter to write but also guarantees there can never be a second instance.
I can think of two reasons:
The first is Encapsulation: you might have second thoughts about how and when your singleton is initialized, after your class has been exposed to client code. And an initialization method gives you more freedom as to changing your strategy later on. For example you might change your mind and decide to use two different constructors instead of one, according to another static variable's value at runtime. With your solution you're bound to using just one constructor at the time your class is loaded into memory, whereas with getInstance() you can change the initialization logic without affecting the interface to the client code.
The second is Lazy Initialization : with the conventional singleton implementation the MyClass object is loaded into memory only when needed by the client code for the first time. And if the client code doesn't need it at all, you save on the memory allocated by your application. Note that whether your singleton is needed or not might not be certain until the program runs. For example it might depend on the user interaction with the program.
However the Lazy Initialization is not something you might necessarily want. For example if you're programming an interactive system and the initialization of your singleton is time consuming, it might actually be better to initialize it when the program is loading rather than when the user is already interacting with it, cause the latter might cause a latency in your system response the first time getInstance() is called. But in this case you can just have your instance initialized with the public method as in:
private static MyClass instance = getInstance();
The best way to synchronize the threads is using Double Checked (to ensure that only one thread will enter the synchronized block at a time and to avoid obtaining the lock every time the code is executed).
public class DoubleCheckLocking {
public static class SearchBox {
private static volatile SearchBox searchBox;
// private attribute of this class
private String searchWord = "";
private String[] list = new String[]{"Stack", "Overflow"};
// private constructor
private SearchBox() {}
// static method to get instance
public static SearchBox getInstance() {
if (searchBox == null) { // first time lock
synchronized (SearchBox.class) {
if (searchBox == null) { // second time lock
searchBox = new SearchBox();
}
}
}
return searchBox;
}
}
Reflection: Reflection can be caused to destroy singleton
property of singleton class, as shown in following example:
// Java code to explain effect of Reflection
import java.lang.reflect.Constructor;
// Singleton class
class Singleton
{
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton()
{
// private constructor
}
}
public class GFG
{
public static void main(String[] args)
{
Singleton instance1 = Singleton.instance;
Singleton instance2 = null;
try
{
Constructor[] constructors =
Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors)
{
// Below code will destroy the singleton pattern
constructor.setAccessible(true);
instance2 = (Singleton) constructor.newInstance();
break;
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("instance1.hashCode():- "
+ instance1.hashCode()); //366712642
System.out.println("instance2.hashCode():- "
+ instance2.hashCode()); //1829164700
}
}

Java: getInstance vs Static

What is the purpose of getInstance() in Java?
During my research I keep reading that getInstance() helps achieve a Singleton design pattern (which means just one instance across the whole program to my understanding). But can't I just use static? Isn't that the whole point of static?
If I were to just have static methods and fields, how would it differ from using getInstance()? Is there a "scope" of static? For example, one instance per method or class?
And if they are different, in what cases would I choose getInstance() over using static?
I apologize if the question is unclear, I am sure I am missing something on the subject matter, I just can't figure out what.
Thank you for any and all advice.
Static will not give you a singleton. Since there is no way of making a top-level class a singleton in Java, you have getInstance methods which will implement some logic to to be sure there is only one instance of a class.
public class Singleton {
private static Singleton singleton;
private Singleton(){ }
public static synchronized Singleton getInstance( ) {
if (singleton == null)
singleton=new Singleton();
return singleton;
}
}
Check out this top answer: Static Classes In Java
The above code will allow only one instance to be created, and it's clean, however as of Java 1.6, it is better to create singleton's as such since it is slightly more elegant IMHO:
public enum MyEnumSingleton {
INSTANCE;
// other useful methods here
}
Source: http://www.vogella.com/tutorials/DesignPatternSingleton/article.html
Singleton
A singleton allows you to use a single reference to a java Object. For example, here is a singleton which contains a number;
public class MySingleton {
private int myNumber;
private static MySingleton instance;
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
private MySingleton() {}
public void setMyNumber(int myNumber) {
this.myNumber = myNumber;
}
public int getMyNumber() {
return myNumber;
}
}
Now we are going to set the value of this number in the A class:
public class A {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
mySingleton.setMyNumber(42);
/*...*/
}
Then, you can access this value from another class:
public class B {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
int number = mySingleton.getMyNumber();
/*...*/
}
In this class the number variable will have the value 42. This is the advantage of a singleton over a simple object:
All the values stored in the singleton will be accessible from
"everywhere".
Static class
The purpose is different, here the advantage is to use an object without having to create it.
For example:
public static class MyStaticClass {
public static void sayHello() {
System.out.println("Hello");
}
}
Now you can use the sayHello() method from any classes by calling:
MyStaticClass.sayHello();
The exact method of implementing a singleton, for example using a factory method called getInstance(), isn't that relevant to the question, which is "static methods vs singleton with instance methods".
Classes are themselves effectively singletons, so from that aspect they are similar.
The main difference is that static methods are not part of class hierarchy - they are not inherited, which means the static method option locks you forever to using that exact class and it can't be referred to in any other way, such being an implementation of some interface or a super class.
Instances however don't have this problem, so you can code for example:
class MySingleton implements SomeInterface {
...
}
SomeInterface instance = MySingleton.getInstance();
I prefer to use static too, but sometimes getInstance() is helpful to have some functions that will be related to the object, in which you can modify variables. if you are simply making some util functions that do not need an instance of an object, use static.
When you are using someone's libraries, you never know if a function body needs a class instance. That's why a lot of library classes are using getInstance().
Instead of checking for null, I like this a little better.
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
}
Called with...
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
//Get the only object available
SingleObject object = SingleObject.getInstance();
}
}
Full code from: http://www.tutorialspoint.com/design_pattern/singleton_pattern.htm
One overlooked reason to use a singleton instead of static class member variables is that the static member variables MAY use space and garbage collector time even in the event the class is never instantiated. Consider how many classes are available to you in rt.jar and what a small fraction of them you probably use in any given application. Also consider that using getInstance ensures your "constructor" has run before any of the member variables are accessed. I almost universally see getInstance as synchronized but I feel this is a bad idea. If anyone ever adds a synchronized blocking method calls to Singleton.getInstance().unsynchronized() could be needlessly held up.
private static Singleton instance = null;
private Singleton() {}
public final static Singleton getInstance() {
return (instance != null) ? instance : makeInstance();
}
private final static synchronized Singleton makeInstance() {
return ( instance != null ) ? instance : ( instance = new Singleton() );
}

What is an efficient way to implement a singleton pattern in Java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
What is an efficient way to implement a singleton design pattern in Java?
Use an enum:
public enum Foo {
INSTANCE;
}
Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video. Also see slides 30-32 of his presentation (effective_java_reloaded.pdf):
The Right Way to Implement a Serializable Singleton
public enum Elvis {
INSTANCE;
private final String[] favoriteSongs =
{ "Hound Dog", "Heartbreak Hotel" };
public void printFavorites() {
System.out.println(Arrays.toString(favoriteSongs));
}
}
Edit: An online portion of "Effective Java" says:
"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."
Depending on the usage, there are several "correct" answers.
Since Java 5, the best way to do it is to use an enum:
public enum Foo {
INSTANCE;
}
Pre Java 5, the most simple case is:
public final class Foo {
private static final Foo INSTANCE = new Foo();
private Foo() {
if (INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return INSTANCE;
}
public Object clone() throws CloneNotSupportedException{
throw new CloneNotSupportedException("Cannot clone instance of this class");
}
}
Let's go over the code. First, you want the class to be final. In this case, I've used the final keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a private static final Foo field to hold the only instance, and a public static Foo getInstance() method to return it. The Java specification makes sure that the constructor is only called when the class is first used.
When you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.
You can use a private static class to load the instance. The code would then look like:
public final class Foo {
private static class FooLoader {
private static final Foo INSTANCE = new Foo();
}
private Foo() {
if (FooLoader.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return FooLoader.INSTANCE;
}
}
Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.
When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.
public final class Foo implements Serializable {
private static final long serialVersionUID = 1L;
private static class FooLoader {
private static final Foo INSTANCE = new Foo();
}
private Foo() {
if (FooLoader.INSTANCE != null) {
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return FooLoader.INSTANCE;
}
#SuppressWarnings("unused")
private Foo readResolve() {
return FooLoader.INSTANCE;
}
}
The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.
Disclaimer: I have just summarized all of the awesome answers and wrote it in my own words.
While implementing Singleton we have two options:
Lazy loading
Early loading
Lazy loading adds bit overhead (lots of to be honest), so use it only when you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization. Otherwise, choosing early loading is a good choice.
The most simple way of implementing a singleton is:
public class Foo {
// It will be our sole hero
private static final Foo INSTANCE = new Foo();
private Foo() {
if (INSTANCE != null) {
// SHOUT
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
return INSTANCE;
}
}
Everything is good except it's an early loaded singleton. Lets try lazy loaded singleton
class Foo {
// Our now_null_but_going_to_be sole hero
private static Foo INSTANCE = null;
private Foo() {
if (INSTANCE != null) {
// SHOUT
throw new IllegalStateException("Already instantiated");
}
}
public static Foo getInstance() {
// Creating only when required.
if (INSTANCE == null) {
INSTANCE = new Foo();
}
return INSTANCE;
}
}
So far so good, but our hero will not survive while fighting alone with multiple evil threads who want many many instance of our hero.
So let’s protect it from evil multi threading:
class Foo {
private static Foo INSTANCE = null;
// TODO Add private shouting constructor
public static Foo getInstance() {
// No more tension of threads
synchronized (Foo.class) {
if (INSTANCE == null) {
INSTANCE = new Foo();
}
}
return INSTANCE;
}
}
But it is not enough to protect out hero, really!!! This is the best we can/should do to help our hero:
class Foo {
// Pay attention to volatile
private static volatile Foo INSTANCE = null;
// TODO Add private shouting constructor
public static Foo getInstance() {
if (INSTANCE == null) { // Check 1
synchronized (Foo.class) {
if (INSTANCE == null) { // Check 2
INSTANCE = new Foo();
}
}
}
return INSTANCE;
}
}
This is called the "double-checked locking idiom". It's easy to forget the volatile statement and difficult to understand why it is necessary.
For details: The "Double-Checked Locking is Broken" Declaration
Now we are sure about evil threads, but what about the cruel serialization? We have to make sure even while de-serialiaztion no new object is created:
class Foo implements Serializable {
private static final long serialVersionUID = 1L;
private static volatile Foo INSTANCE = null;
// The rest of the things are same as above
// No more fear of serialization
#SuppressWarnings("unused")
private Object readResolve() {
return INSTANCE;
}
}
The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of our program.
Finally, we have added enough protection against threads and serialization, but our code is looking bulky and ugly. Let’s give our hero a makeover:
public final class Foo implements Serializable {
private static final long serialVersionUID = 1L;
// Wrapped in a inner static class so that loaded only when required
private static class FooLoader {
// And no more fear of threads
private static final Foo INSTANCE = new Foo();
}
// TODO add private shouting construcor
public static Foo getInstance() {
return FooLoader.INSTANCE;
}
// Damn you serialization
#SuppressWarnings("unused")
private Foo readResolve() {
return FooLoader.INSTANCE;
}
}
Yes, this is our very same hero :)
Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread-safe.
And we have come so far. Here is the best way to achieve everything we did is best possible way:
public enum Foo {
INSTANCE;
}
Which internally will be treated like
public class Foo {
// It will be our sole hero
private static final Foo INSTANCE = new Foo();
}
That's it! No more fear of serialization, threads and ugly code. Also ENUMS singleton are lazily initialized.
This approach is functionally equivalent to the public field approach,
except that it is more concise, provides the serialization machinery
for free, and provides an ironclad guarantee against multiple
instantiation, even in the face of sophisticated serialization or
reflection attacks. While this approach has yet to be widely adopted,
a single-element enum type is the best way to implement a singleton.
-Joshua Bloch in "Effective Java"
Now you might have realized why ENUMS are considered as best way to implement a singleton and thanks for your patience :)
Updated it on my blog.
The solution posted by Stu Thompson is valid in Java 5.0 and later. But I would prefer not to use it because I think it is error prone.
It's easy to forget the volatile statement and difficult to understand why it is necessary. Without the volatile this code would not be thread safe any more due to the double-checked locking antipattern. See more about this in paragraph 16.2.4 of Java Concurrency in Practice. In short: This pattern (prior to Java 5.0 or without the volatile statement) could return a reference to the Bar object that is (still) in an incorrect state.
This pattern was invented for performance optimization. But this is really not a real concern any more. The following lazy initialization code is fast and - more importantly - easier to read.
class Bar {
private static class BarHolder {
public static Bar bar = new Bar();
}
public static Bar getBar() {
return BarHolder.bar;
}
}
Thread safe in Java 5+:
class Foo {
private static volatile Bar bar = null;
public static Bar getBar() {
if (bar == null) {
synchronized(Foo.class) {
if (bar == null)
bar = new Bar();
}
}
return bar;
}
}
Pay attention to the volatile modifier here. :) It is important because without it, other threads are not guaranteed by the JMM (Java Memory Model) to see changes to its value. The synchronization does not take care of that--it only serializes access to that block of code.
#Bno's answer details the approach recommended by Bill Pugh (FindBugs) and is arguable better. Go read and vote up his answer too.
Forget lazy initialization; it's too problematic. This is the simplest solution:
public class A {
private static final A INSTANCE = new A();
private A() {}
public static A getInstance() {
return INSTANCE;
}
}
Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments against it.
There's nothing inherently wrong with it I suppose, but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I've found dependency injection (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.
I'm mystified by some of the answers that suggest dependency injection (DI) as an alternative to using singletons; these are unrelated concepts. You can use DI to inject either singleton or non-singleton (e.g., per-thread) instances. At least this is true if you use Spring 2.x, I can't speak for other DI frameworks.
So my answer to the OP would be (in all but the most trivial sample code) to:
Use a DI framework like Spring Framework, then
Make it part of your DI configuration whether your dependencies are singletons, request scoped, session scoped, or whatever.
This approach gives you a nice decoupled (and therefore flexible and testable) architecture where whether to use a singleton is an easily reversible implementation detail (provided any singletons you use are threadsafe, of course).
Really consider why you need a singleton before writing it. There is a quasi-religious debate about using them which you can quite easily stumble over if you google singletons in Java.
Personally, I try to avoid singletons as often as possible for many reasons, again most of which can be found by googling singletons. I feel that quite often singletons are abused because they're easy to understand by everybody. They're used as a mechanism for getting "global" data into an OO design and they are used because it is easy to circumvent object lifecycle management (or really thinking about how you can do A from inside B). Look at things like inversion of control (IoC) or dependency injection (DI) for a nice middle ground.
If you really need one then Wikipedia has a good example of a proper implementation of a singleton.
Following are three different approaches
Enum
/**
* Singleton pattern example using Java Enum
*/
public enum EasySingleton {
INSTANCE;
}
Double checked locking / lazy loading
/**
* Singleton pattern example with Double checked Locking
*/
public class DoubleCheckedLockingSingleton {
private static volatile DoubleCheckedLockingSingleton INSTANCE;
private DoubleCheckedLockingSingleton() {}
public static DoubleCheckedLockingSingleton getInstance() {
if(INSTANCE == null) {
synchronized(DoubleCheckedLockingSingleton.class) {
// Double checking Singleton instance
if(INSTANCE == null) {
INSTANCE = new DoubleCheckedLockingSingleton();
}
}
}
return INSTANCE;
}
}
Static factory method
/**
* Singleton pattern example with static factory method
*/
public class Singleton {
// Initialized during class loading
private static final Singleton INSTANCE = new Singleton();
// To prevent creating another instance of 'Singleton'
private Singleton() {}
public static Singleton getSingleton() {
return INSTANCE;
}
}
There is a lot of nuance around implementing a singleton. The holder pattern can not be used in many situations. And IMO when using a volatile - you should also use a local variable. Let's start at the beginning and iterate on the problem. You'll see what I mean.
The first attempt might look something like this:
public class MySingleton {
private static MySingleton INSTANCE;
public static MySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new MySingleton();
}
return INSTANCE;
}
...
}
Here we have the MySingleton class which has a private static member called INSTANCE, and a public static method called getInstance(). The first time getInstance() is called, the INSTANCE member is null. The flow will then fall into the creation condition and create a new instance of the MySingleton class. Subsequent calls to getInstance() will find that the INSTANCE variable is already set, and therefore not create another MySingleton instance. This ensures there is only one instance of MySingleton which is shared among all callers of getInstance().
But this implementation has a problem. Multi-threaded applications will have a race condition on the creation of the single instance. If multiple threads of execution hit the getInstance() method at (or around) the same time, they will each see the INSTANCE member as null. This will result in each thread creating a new MySingleton instance and subsequently setting the INSTANCE member.
private static MySingleton INSTANCE;
public static synchronized MySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new MySingleton();
}
return INSTANCE;
}
Here we’ve used the synchronized keyword in the method signature to synchronize the getInstance() method. This will certainly fix our race condition. Threads will now block and enter the method one at a time. But it also creates a performance problem. Not only does this implementation synchronize the creation of the single instance; it synchronizes all calls to getInstance(), including reads. Reads do not need to be synchronized as they simply return the value of INSTANCE. Since reads will make up the bulk of our calls (remember, instantiation only happens on the first call), we will incur an unnecessary performance hit by synchronizing the entire method.
private static MySingleton INSTANCE;
public static MySingleton getInstance() {
if (INSTANCE == null) {
synchronize(MySingleton.class) {
INSTANCE = new MySingleton();
}
}
return INSTANCE;
}
Here we’ve moved synchronization from the method signature, to a synchronized block that wraps the creation of the MySingleton instance. But does this solve our problem? Well, we are no longer blocking on reads, but we’ve also taken a step backward. Multiple threads will hit the getInstance() method at or around the same time and they will all see the INSTANCE member as null.
They will then hit the synchronized block where one will obtain the lock and create the instance. When that thread exits the block, the other threads will contend for the lock, and one by one each thread will fall through the block and create a new instance of our class. So we are right back where we started.
private static MySingleton INSTANCE;
public static MySingleton getInstance() {
if (INSTANCE == null) {
synchronized(MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = createInstance();
}
}
}
return INSTANCE;
}
Here we issue another check from inside the block. If the INSTANCE member has already been set, we’ll skip initialization. This is called double-checked locking.
This solves our problem of multiple instantiation. But once again, our solution has presented another challenge. Other threads might not “see” that the INSTANCE member has been updated. This is because of how Java optimizes memory operations.
Threads copy the original values of variables from main memory into the CPU’s cache. Changes to values are then written to, and read from, that cache. This is a feature of Java designed to optimize performance. But this creates a problem for our singleton implementation. A second thread — being processed by a different CPU or core, using a different cache — will not see the changes made by the first. This will cause the second thread to see the INSTANCE member as null forcing a new instance of our singleton to be created.
private static volatile MySingleton INSTANCE;
public static MySingleton getInstance() {
if (INSTANCE == null) {
synchronized(MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = createInstance();
}
}
}
return INSTANCE;
}
We solve this by using the volatile keyword on the declaration of the INSTANCE member. This will tell the compiler to always read from, and write to, main memory, and not the CPU cache.
But this simple change comes at a cost. Because we are bypassing the CPU cache, we will take a performance hit each time we operate on the volatile INSTANCE member — which we do four times. We double-check existence (1 and 2), set the value (3), and then return the value (4). One could argue that this path is the fringe case as we only create the instance during the first call of the method. Perhaps a performance hit on creation is tolerable. But even our main use-case, reads, will operate on the volatile member twice. Once to check existence, and again to return its value.
private static volatile MySingleton INSTANCE;
public static MySingleton getInstance() {
MySingleton result = INSTANCE;
if (result == null) {
synchronized(MySingleton.class) {
result = INSTANCE;
if (result == null) {
INSTANCE = result = createInstance();
}
}
}
return result;
}
Since the performance hit is due to operating directly on the volatile member, let’s set a local variable to the value of the volatile and operate on the local variable instead. This will decrease the number of times we operate on the volatile, thereby reclaiming some of our lost performance. Note that we have to set our local variable again when we enter the synchronized block. This ensures it is up to date with any changes that occurred while we were waiting for the lock.
I wrote an article about this recently. Deconstructing The Singleton. You can find more information on these examples and an example of the "holder" pattern there. There is also a real-world example showcasing the double-checked volatile approach.
I use the Spring Framework to manage my singletons.
It doesn't enforce the "singleton-ness" of the class (which you can't really do anyway if there are multiple class loaders involved), but it provides a really easy way to build and configure different factories for creating different types of objects.
Wikipedia has some examples of singletons, also in Java. The Java 5 implementation looks pretty complete, and is thread-safe (double-checked locking applied).
Version 1:
public class MySingleton {
private static MySingleton instance = null;
private MySingleton() {}
public static synchronized MySingleton getInstance() {
if(instance == null) {
instance = new MySingleton();
}
return instance;
}
}
Lazy loading, thread safe with blocking, low performance because of synchronized.
Version 2:
public class MySingleton {
private MySingleton() {}
private static class MySingletonHolder {
public final static MySingleton instance = new MySingleton();
}
public static MySingleton getInstance() {
return MySingletonHolder.instance;
}
}
Lazy loading, thread safe with non-blocking, high performance.
If you do not need lazy loading then simply try:
public class Singleton {
private final static Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() { return Singleton.INSTANCE; }
protected Object clone() {
throw new CloneNotSupportedException();
}
}
If you want lazy loading and you want your singleton to be thread-safe, try the double-checking pattern:
public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if(null == instance) {
synchronized(Singleton.class) {
if(null == instance) {
instance = new Singleton();
}
}
}
return instance;
}
protected Object clone() {
throw new CloneNotSupportedException();
}
}
As the double checking pattern is not guaranteed to work (due to some issue with compilers, I don't know anything more about that), you could also try to synchronize the whole getInstance-method or create a registry for all your singletons.
I would say an enum singleton.
Singleton using an enum in Java is generally a way to declare an enum singleton. An enum singleton may contain instance variables and instance methods. For simplicity's sake, also note that if you are using any instance method then you need to ensure thread safety of that method if at all it affects the state of object.
The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.
/**
* Singleton pattern example using a Java Enum
*/
public enum Singleton {
INSTANCE;
public void execute (String arg) {
// Perform operation here
}
}
You can access it by Singleton.INSTANCE, and it is much easier than calling the getInstance() method on Singleton.
1.12 Serialization of Enum Constants
Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form. To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.lang.Enum.valueOf method, passing the constant's enum type along with the received constant name as arguments. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream.
The process by which enum constants are serialized cannot be customized: any class-specific writeObject, readObject, readObjectNoData, writeReplace, and readResolve methods defined by enum types are ignored during serialization and deserialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored--all enum types have a fixed serialVersionUID of 0L. Documenting serializable fields and data for enum types is unnecessary, since there is no variation in the type of data sent.
Quoted from Oracle documentation
Another problem with conventional Singletons are that once you implement the Serializable interface, they no longer remain singleton because the readObject() method always return a new instance, like a constructor in Java. This can be avoided by using readResolve() and discarding the newly created instance by replacing with a singleton like below:
// readResolve to prevent another instance of Singleton
private Object readResolve(){
return INSTANCE;
}
This can become even more complex if your singleton class maintains state, as you need to make them transient, but with in an enum singleton, serialization is guaranteed by the JVM.
Good Read
Singleton Pattern
Enums, Singletons and Deserialization
Double-checked locking and the Singleton pattern
There are four ways to create a singleton in Java.
Eager initialization singleton
public class Test {
private static final Test test = new Test();
private Test() {
}
public static Test getTest() {
return test;
}
}
Lazy initialization singleton (thread safe)
public class Test {
private static volatile Test test;
private Test() {
}
public static Test getTest() {
if(test == null) {
synchronized(Test.class) {
if(test == null) {
test = new Test();
}
}
}
return test;
}
}
Bill Pugh singleton with holder pattern (preferably the best one)
public class Test {
private Test() {
}
private static class TestHolder {
private static final Test test = new Test();
}
public static Test getInstance() {
return TestHolder.test;
}
}
Enum singleton
public enum MySingleton {
INSTANCE;
private MySingleton() {
System.out.println("Here");
}
}
This is how to implement a simple singleton:
public class Singleton {
// It must be static and final to prevent later modification
private static final Singleton INSTANCE = new Singleton();
/** The constructor must be private to prevent external instantiation */
private Singleton(){}
/** The public static method allowing to get the instance */
public static Singleton getInstance() {
return INSTANCE;
}
}
This is how to properly lazy create your singleton:
public class Singleton {
// The constructor must be private to prevent external instantiation
private Singleton(){}
/** The public static method allowing to get the instance */
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
/**
* The static inner class responsible for creating your instance only on demand,
* because the static fields of a class are only initialized when the class
* is explicitly called and a class initialization is synchronized such that only
* one thread can perform it, this rule is also applicable to inner static class
* So here INSTANCE will be created only when SingletonHolder.INSTANCE
* will be called
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
}
You need the double-checking idiom if you need to load the instance variable of a class lazily. If you need to load a static variable or a singleton lazily, you need the initialization on demand holder idiom.
In addition, if the singleton needs to be serializable, all other fields need to be transient and readResolve() method needs to be implemented in order to maintain the singleton object invariant. Otherwise, each time the object is deserialized, a new instance of the object will be created. What readResolve() does is replace the new object read by readObject(), which forced that new object to be garbage collected as there is no variable referring to it.
public static final INSTANCE == ....
private Object readResolve() {
return INSTANCE; // Original singleton instance.
}
Various ways to make a singleton object:
As per Joshua Bloch - Enum would be the best.
You can use double check locking also.
Even an inner static class can be used.
Enum singleton
The simplest way to implement a singleton that is thread-safe is using an Enum:
public enum SingletonEnum {
INSTANCE;
public void doSomething(){
System.out.println("This is a singleton");
}
}
This code works since the introduction of Enum in Java 1.5
Double checked locking
If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.
public class Singleton {
private static volatile Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class){
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.
Early loading singleton (works even before Java 1.5)
This implementation instantiates the singleton when the class is loaded and provides thread safety.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
public void doSomething(){
System.out.println("This is a singleton");
}
}
For JSE 5.0 and above, take the Enum approach. Otherwise, use the static singleton holder approach ((a lazy loading approach described by Bill Pugh). The latter solution is also thread-safe without requiring special language constructs (i.e., volatile or synchronized).
Another argument often used against singletons is their testability problems. Singletons are not easily mockable for testing purposes. If this turns out to be a problem, I like to make the following slight modification:
public class SingletonImpl {
private static SingletonImpl instance;
public static SingletonImpl getInstance() {
if (instance == null) {
instance = new SingletonImpl();
}
return instance;
}
public static void setInstance(SingletonImpl impl) {
instance = impl;
}
public void a() {
System.out.println("Default Method");
}
}
The added setInstance method allows setting a mockup implementation of the singleton class during testing:
public class SingletonMock extends SingletonImpl {
#Override
public void a() {
System.out.println("Mock Method");
}
}
This also works with early initialization approaches:
public class SingletonImpl {
private static final SingletonImpl instance = new SingletonImpl();
private static SingletonImpl alt;
public static void setInstance(SingletonImpl inst) {
alt = inst;
}
public static SingletonImpl getInstance() {
if (alt != null) {
return alt;
}
return instance;
}
public void a() {
System.out.println("Default Method");
}
}
public class SingletonMock extends SingletonImpl {
#Override
public void a() {
System.out.println("Mock Method");
}
}
This has the drawback of exposing this functionality to the normal application too. Other developers working on that code could be tempted to use the ´setInstance´ method to alter a specific function and thus changing the whole application behaviour, and therefore this method should contain at least a good warning in its javadoc.
Still, for the possibility of mockup-testing (when needed), this code exposure may be an acceptable price to pay.
Simplest singleton class:
public class Singleton {
private static Singleton singleInstance = new Singleton();
private Singleton() {}
public static Singleton getSingleInstance() {
return singleInstance;
}
}
Have a look at this post.
Examples of GoF Design Patterns in Java's core libraries
From the best answer's "Singleton" section,
Singleton (recognizeable by creational methods returning the same instance (usually of itself) everytime)
java.lang.Runtime#getRuntime()
java.awt.Desktop#getDesktop()
java.lang.System#getSecurityManager()
You can also learn the example of Singleton from Java native classes themselves.
The best singleton pattern I've ever seen uses the Supplier interface.
It's generic and reusable
It supports lazy initialization
It's only synchronized until it has been initialized, then the blocking supplier is replaced with a non-blocking supplier.
See below:
public class Singleton<T> implements Supplier<T> {
private boolean initialized;
private Supplier<T> singletonSupplier;
public Singleton(T singletonValue) {
this.singletonSupplier = () -> singletonValue;
}
public Singleton(Supplier<T> supplier) {
this.singletonSupplier = () -> {
// The initial supplier is temporary; it will be replaced after initialization
synchronized (supplier) {
if (!initialized) {
T singletonValue = supplier.get();
// Now that the singleton value has been initialized,
// replace the blocking supplier with a non-blocking supplier
singletonSupplier = () -> singletonValue;
initialized = true;
}
return singletonSupplier.get();
}
};
}
#Override
public T get() {
return singletonSupplier.get();
}
}
I still think after Java 1.5, enum is the best available singleton implementation available as it also ensures that, even in the multi threaded environments, only one instance is created.
public enum Singleton {
INSTANCE;
}
And you are done!
Sometimes a simple "static Foo foo = new Foo();" is not enough. Just think of some basic data insertion you want to do.
On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution is
public class Singleton {
private static Singleton instance = null;
static {
instance = new Singleton();
// do some of your instantiation stuff here
}
private Singleton() {
if(instance!=null) {
throw new ErrorYouWant("Singleton double-instantiation, should never happen!");
}
}
public static getSingleton() {
return instance;
}
}
Now what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the static { } - block. that's the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
if (INSTANCE != null)
throw new IllegalStateException(“Already instantiated...”);
}
public synchronized static Singleton getInstance() {
return INSTANCE;
}
}
As we have added the Synchronized keyword before getInstance, we have avoided the race condition in the case when two threads call the getInstance at the same time.

Categories