Singleton means one instance throughout the application(Java Virtual Machine).It is used to provide global point of access to the object. In terms of practical use Singleton patterns are used in logging, caches, configuration settings etc.It is mostly used in conjunction with the Factory Design Pattern.
The below example shows a very basic implementation of singleton class
The below example shows a very basic implementation of singleton class
public class Singleton {
private static Singleton singletonInstance;
private Singleton() {
}
public static Singleton getSingletonInstance() {
if (null == singletonInstance) {
singletonInstance = new Singleton();
}
return singletonInstance;
}
}
However this does not take care of thread safety . A better implementation will be like as follows
public class Singleton {
private static Singleton singletonInstance;
private Singleton() {
}
public static synchronized Singleton getSingletonInstance() {
if (null == singletonInstance) {
singletonInstance = new Singleton();
}
return singletonInstance;
}
}
A more better implementation can be as follows -
public class Singleton {
private static Singleton singletonInstance;
private static Object mutex = new Object();
private Singleton() {
}
public static Singleton getSingletonInstance() {
if (null == singletonInstance) {
synchronized(mutex){
singletonInstance = new Singleton();
}
}
return singletonInstance;
}
}
The second example for singleton implementation guarantees thread safety but will result in poor performance as method level thread lock is acquired . The third will do synchronization only if we need to create a new instance of the singletonInstance object. This will guarantee a best performance from the above three examples.
