Proper Implementation Of Singleton Pattern in Java

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

How Most People Implement Singleton Pattern in Java

Below is an example of the Singleton design pattern most people implement in Java. What’s wrong with the following codes? At first, it may not be obvious. If our application is simple and not mission-critical, those codes may just perform well enough.

First, a call to getInstance() is expensive as it is synchronized even after the codes instantiated the class. Therefore, it may impact performance. Second, only one thread at a time can run the method. What if somewhere in our codes we made similar simultaneous calls to hundreds of different classes at a critical time of the application? Furthermore, how about those third-party library codes in case they use the same approach to creating Singleton objects?

The Proper Implementation

At any rate in our projects, we should strive for proper implementation. Sometimes this is not easy because of external influences. Below the codes of proper implementation of the Singleton design pattern in Java. First, we don’t use the synchronized keyword on the method. Instead, we apply it to our class after checking for null values. Therefore, we only perform the expensive operation of synchronization ones (or a few times). As a result, the codes are performant.

Second, we need to use the volatile keyword on our instance variable. The usage of volatile prevents subtle cases where the compiler performs optimization on the codes such that the object is accessed before it is completely constructed.

That’s how we should implement the Singleton design pattern in Java! So, how about the @Singleton objects in Spring? We can still mark them as @Lazy, right? Well, the Spring container does the job of synchronizing threads.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like