How to create thread-safe singleton objects in Java?
How to create thread-safe singleton objects in Java?
The easiest way to create a thread-safe singleton class is to make the getInstance method synchronized thereby allowing only one thread to execute this method at a time.
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Above code works fine and provides thread-safety but it reduces performance because of cost associated with the synchronized method. It can be noticed that this design is not optimal as every invocation of getInstance method is synchronized while the requirement is only for the first call. A slightly better solution is to synchronize only the new instance creation instead of the entire method. This solution requires an additional check for null inside the synchronized block and is termed as double check locking optimization.
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}