All possible ways of implementing singleton pattern and its pros and cons
October 9, 2012 4 Comments
Here 5 possible ways are discussed
#1
public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } }
Cons:
Will not suffice for multi threaded environment
#2
public class Singleton { private static Singleton instance; private Singleton() { } public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } }
pros:
Will work in single and multithreaded env’s
Cons:
Will be uneccessary overhead once after instance is created for the first time because every time we call getInstance() method we need to acquire lock and release lock which is overhead after instance is available
#3
public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { synchronized(this) { if(instance == null) { instance = new Singleton(); } } return instance; } }
pros:
Will not suffice in multithreaded env’s
Cons:
1. Will be uneccessary overhead once after instance is created for the first time because every time we call getInstance() method we need to acquire lock and release lock which is overhead after instance is available
2. There is a chance of more than one thread getting into if(instance == null) block there by creating multiple instances.
#4 (Double Checking)
public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if(instance == null) { synchronized(this) { if(instance == null) { instance = new Singleton(); } } } return instance; } }
pros:
Will work in multithreaded env’s
Cons:
1. It will not work in prior versions of JDK5.0
2. Double checking is verey pathetic way of implementing Singleton pattern and best practices doesnt suggest to go for this implementation.
#5
public class Singleton { private static Singleton instance = new Singleton(); private Singleton() { } public static Singleton getInstance() { return instance; } }
pros:
1. Simplest and trusted way as we are leaving the instantiation to the JVM
2. Works in both single and multithreaded env’s
Pingback: All possible ways of implementing singleton pattern and its pros and cons « urpalananth
u mean to ask sth here
Not in sarcastic way but would love to know if there’s any documentation in java spec that states instantiation to the JVM is thread safe.
regards!
didnt come through any java spec as such but from my understanding:
– Class will be loaded only once into the JVM no matter how many threads are trying to access this instance
– Lets assume two threads entered “getInstance()” method in approach-5, even before they entered this method the class would already have been loaded into JVM and hence two threads would be getting same instance