Software Development

Proper implementation of Singleton Pattern in Java

This post demonstrates the proper implementation of Singleton Pattern in Java. Most of us would apply Singleton Pattern in the most convenient way for us but not the proper implementation. In most cases, our codes would work. But when we deal with concurrency stuff and mission-critical applications, subtle issues may arise that are really hard to debug and figure out the root cause of.

What most people do

What’s wrong with the following codes? Well, a call to getInstance() is expensive as it is synchronized even after an instance of the class has been created and can impact performance.


The Proper Implementation

In this implementation, we first check if instance is null. If it’s true, only then we apply synchronization on the class while creating an instance of the same class. Subsequent call to getInstance() is not synchronized and therefore will not impact performance.


The usage of volatile is to prevent subtle cases where the compiler performs optimization on the codes such that the object is accessed before it is completely constructed.

You Might Also Like