Singleton Pattern #3: Problems with Singleton, Thread-Safe Singleton Class

A side effect of using singleton class: as the constructor of the singleton class is private, you cannot create a subclass of a singleton class, but in most of the cases that is desirable. Additionally you can declare the class as final to explicitly show that the class can’t be subclassed. But in case if it is required to create a subclass of singleton class one can define the constructor of singleton class as protective instead of private.

Another point to note is that the singleton classes are not thread-safe. Simply putting it if the two threads enter the

If(instance==null)
{
//create new instance.
}

block simultaneously, it will create two different instances of the class. This is an undesirable condition and cause unwanted behavior in the application. Also note here that in case of eager instantiation this problem does not occur as the instance gets created beforehand.

Making your singleton class thread-safe is easy, you just have to make your getinstance method synchronized.

Public synchronized static singletonExample getInstance()
{
//if instance is null create else return old instance
}

Originally posted February 15, 2007

Brought back using archive.org