Singleton pattern in MultiThreaded Environment
- 12 Comment
Singleton pattern, as we all know restricts instantiation of a class to single object. In this article, I’ll talk about the issues coming up due to Singleton pattern in MultiThreading environment. Also, I would like to discuss an alternate implementation of singleton pattern in java.
The Problem:
In our project, we were loading an xml file in the constructor of the Singleton class. It appeared to be very simple but we faced an unexpected exception. As the article proceeds, we’ll discuss the problem and its solution towards the end.
The basic design of Singleton is known to most of us, but I’ll write a brief code based on common singleton and then we will quickly proceed further.
class DateCounterInfoFile { private static DateCounterInfoFile dateCounterInfoFile; private DateCounterInfoFile() { this.loadDateCounterMap(_fileName); //loading xml in constructor } public static DateCounterInfoFile getInstance() { if (dateCounterInfoFile == null) dateCounterInfoFile = new DateCounterInfoFile(); return dateCounterInfoFile; } } |
The above example shows that only one object of DateCounterInfoFile class is created. The above implementation works fine in a single-threaded environment. However, in case of multiple threads, we must protect the method getInstance() by using synchronization.
Now, lets see Singleton in MultiThreaded environment:
class DateCounterInfoFile { private static DateCounterInfoFile dateCounterInfoFile; private DateCounterInfoFile() { this.loadDateCounterMap(_fileName); //loads an xml file } public static Singleton getInstance() { if (dateCounterInfoFile == null) //1 { synchronized(DateCounterInfoFile.class) //2 { if (dateCounterInfoFile == null) //3 dateCounterInfoFile = new DateCounterInfoFile(); //4 } } return dateCounterInfoFile; }} |
In the above code, we are checking for dateCounterInfoFile two times. This implementation is called ‘double-checked locking’. Now, here comes the real problem!!
We synchronized a block and used double-checked locking to ensure that everything goes fine, but alas! our code was breaking. Lets analyze what was happening:
As you can see, inside the private constructor of DateCounterInfoFile class, we have called a function, which loads the xml file. Now this code was giving us ‘Null Pointer Exception’. Let me explain to you what was really happening.
-
Thread 1 enters line 1 and checks that instance of DateCounterInfoFile is null.
-
It enters synchronized block at line 2 and makes instance not null at line 4.
-
Thread 1 is preempted by Thread 2 after memory is allocated to DateCounterInfoFile object but before it is initialized(we’ll get back to this after a short while).
-
Now Thread 2 enters line 1 and finds that DateCounterInfoFile object is not null and returns partially initialized object.
-
Now Thread 2 is preempted by Thread 1 again and Thread 1 completes initialization of DateCounterInfoFile object and returns fully initialized object.
-
Thus, we are left with 2 objects of our class, among which one is partially constructed and other is fully constructed.
Let’s see, what happens when ‘dateCounterInfoFile = new dateCounterInfoFile()’ compiles:
It is broken down into three simple steps;
-
mem = allocate (memory is allocated for the object)
-
dateCounterInfoFile = mem(Thus, dateCounterInfoFile becomes not null but it is not initialized)
-
constructor is invoked.
Thus, going back to point 3 we find Thread 2 preempt Thread 1 just before constructor is invoked and just after memory is allocated!
So, when we tried to run our code, it gave unpredictable results. Some times it used to run properly while sometimes, it threw ‘Null Pointer Exception’ at us as the constructor didnt execute fully which left us with no xml file loaded(Note - we were trying to load our xml file inside the constructor).
So, to avoid this problem, java 5 gives us one solution – Volatile. We can make the dateCounterInfoFile reference as Volatile. In Java 5, volatile variable behaves mostly as synchronization. It ensures that volatile read must happen after the write has taken place. Thus in this way, reading thread will always see the correct value of variable dateCounterInfoFile.
Thus, the code becomes:
class DateCounterInfoFile { private static volatile DateCounterInfoFile dateCounterInfoFile; . . . Rest of the code remains the same as above.
}
But, when variables are declared volatile, they are reconciled with main memory on every access. On the other hand, when synchronization is used, the variables are reconciled with main memory only when lock is obtained and lock is released. Thus, using volatile might be slower than synchronization.
To overcome this problem, we took advantage of Bill Pugh solution. The solution is thread safe and does not uses either ‘volatile’ or ‘synchronization’.
The solution:
class DateCounterInfoFile { private static DateCounterInfoFile dateCounterInfoFile; private DateCounterInfoFile() { this.loadDateCounterMap(_fileName); //loads an xml file } private static class SingletonHolder { private final static DateCounterInfoFile dateCounterInfoFile = new DateCounterInfoFile(); } public static DateCounterInfoFile getInstance() { Return SingletonHolder.dateCounterInfoFile; } }
Here, as we can see, SingletonHolder is loaded on the first execution of getInstance() method. This technique is also known as ‘lazy Initialization’ or ‘Initialization on demand’.
After using this code, our program ran fine. Thanks to Bill Pugh!!!

Thanks Sumita. It was a great article.
Absolutely great article. very well explained. This would help me not repeat this mistake.
A huge applause from my side for your nice effort
good example,this helped me to understand as i am learning it,am new to it…thanx
nice aticle. really helps me out clearing my doubts on singleton as well as multithreading.
very true. probably we could have skiped lazy initializaion.Life would have been easier.
its good to see that its written in such a professional style by u.
Nice article I had just finishing making the same mistake before finding this article.
wouldn’t be the following code work?
static{
dateCounterInfoFile = new DateCounterInfoFile();
}
public static Singleton getInstance(){
= return dateCounterInfoFile;
}
since static block will be executed at time of class loading, so instead of creating new static inner class, I felt the above approach is easy. what is your comments
What if the “fileName” keeps changing and is not fixed.
@tirupathi
According to me inner class would be shared amongst all the instances of the outer class wereas the static block would be executed for every instance which would lead to multiple constructor call for outer class.