Singleton Class in Java

A singleton is simply a class that is instantiated exactly once in the 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, thread pools, configuration settings, device driver objects. The intention is to create a single instance of a object of classes which are expensive to create during runtime and try to reuse the same object. Such objects are mainly immutable.

The above code look resonably correct. It may fail in multithreaded environment, where Thread1 see that obj is null and enters the if loop to create obj and at the same time Thread2 also comes and find obj as null and enters the loop and create another object. This would result in having multiple instances of singleton class. This problem can be solved by Double Locking.

Lets see what happening in above code. In the above code snippet imagine that multiple threads comes concurrently and tries to create the new instance. In such situation there may be three or more threads are waiting on the synchronized block to get access. Since we have used synchronized only one thread will be given access. All the remaining threads which were waiting on the synchronized block will be given access when first thread exits this block. However when the remaining concurrent thread enters the synchronized block they are prevented to enter further due to the double check : null check. Since the first thread has already created an instance no other thread will enter this loop.

With JDK 1.5 enum (preferred approach). Since Enum is thread safe, its become simplest to implement.