Skip to main content

Posts

Showing posts from July, 2012

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 = INSTA…