Why we need double check in singleton class in java? – Answered

Answer to why we need double check locking in singleton class in Java with thread program example.

 

Let’s understand first what does double checking means?

 

Consider the method getInstance() of below singleton class. You will see there are two if conditions to check if the singleton class object is null. So, question is, if without having first if condition check the program can work fine, then why to use this?

 

 

Before answer to this interview questions, let’s have a complete example of threads and singleton class for double checking (2 if conditions to check if object is null) in java.

 

In this example, we have a singleton class in which we have used double check condition to create a unique object of the singleton class.

 

We have created five threads and they will try to enter critical section to create object of the singleton class.

 

 

Double checked locking in singleton java example

 

 

 

Answer

Have double check to avoid performance issue.

Repeated Locking and unlocking make the program slow. For smaller number of threads, you will not notice, but consider thousands of threads then it is noticed.

In the above example, if you don’t have first check, then every time a thread come, lock will be performed. If thousands of threads…thousands of time lock will be performed.

If you have double check…only one-time lock will be performed.