Java: Singleton class - double-checked locking
Most of the singleton class implementation i have seen are inefficient or buggy specially in multithreaded environment. So, here is my two cents on singleton classes.
We can implement singleton class based on
- Eager instantiation and
- Lazy instantiation
Singleton class based on eager instantiation
In “Effective Java” Josh Bloch preferred using single element enum type to implement singleton class.
public enum Singleton { ISTANCE; //other methods }
Singleton class based on lazy instantiation
Some developer use synchronized method to make method thread safe but it make your function very slow. Other way to make function thread safe is synchronized block. But incorrect use of it, will result in same performance bottleneck.
Here is the preferred way to make singleton class thread safe. (“double-checked locking” algorithm).
public class Singleton { private static volatile Singleton INSTANCE = null; private Singleton(){} public static Singleton getInstance(){ Singleton inst = INSTANCE; if(inst == null){ //first check synchronized (Singleton.class) { inst = INSTANCE; if(inst == null){ //second check INSTANCE = inst = new Singleton(); } } } return INSTANCE; } //other methods }
In above implementation we have two check before creating a new instance of singleton class, and because of this it is known as double lock checking.
Read more about singleton class and "Double-checked locking" on http://en.wikipedia.org/wiki/Double-checked_locking and http://www.ibm.com/developerworks/java/library/j-dcl/index.html
Comments
Post a Comment