Singletons in Java are very similar to C#, being as both languages are object orientated. Below is an example of a singleton class, where only one version of the object can be alive during the program's lifetime (Assuming the program works on one thread)
public class SingletonExample {
private SingletonExample() { }
private static SingletonExample _instance;
public static SingletonExample getInstance() {
if (_instance == null) {
_instance = new SingletonExample();
}
return _instance;
}
}
Here is the thread safe version of that program:
public class SingletonThreadSafeExample {
private SingletonThreadSafeExample () { }
private static volatile SingletonThreadSafeExample _instance;
public static SingletonThreadSafeExample getInstance() {
if (_instance == null) {
createInstance();
}
return _instance;
}
private static void createInstance() {
synchronized(SingletonThreadSafeExample.class) {
if (_instance == null) {
_instance = new SingletonThreadSafeExample();
}
}
}
}
Java also have an object called ThreadLocal
, which creates a single instance of an object on a thread by thread basis. This could be useful in applications where each thread need its own version of the object
public class SingletonThreadLocalExample {
private SingletonThreadLocalExample () { }
private static ThreadLocal<SingletonThreadLocalExample> _instance = new ThreadLocal<SingletonThreadLocalExample>();
public static SingletonThreadLocalExample getInstance() {
if (_instance.get() == null) {
_instance.set(new SingletonThreadLocalExample());
}
return _instance.get();
}
}
Here is also a Singleton implementation with enum
(containing only one element):
public enum SingletonEnum {
INSTANCE;
// fields, methods
}
Any Enum class implementation ensures that there is only one instance of its each element will exist.
Bill Pugh Singleton Pattern
Bill Pugh Singleton Pattern is the most widely used approach for Singleton class as it doesn’t require synchronization
public class SingletonExample {
private SingletonExample(){}
private static class SingletonHolder{
private static final SingletonExample INSTANCE = new SingletonExample();
}
public static SingletonExample getInstance(){
return SingletonHolder.INSTANCE;
}
}
with using private inner static class the holder is not loaded to memory until someone call the getInstance method. Bill Pugh solution is thread safe and it doesn't required synchronization.
There are more Java singleton examples in the Singletons topic under the Java documentation tag.