Saturday 14 January 2012

Code Design for Singleton / Lazy initialization Concurrency

This post is an experiment on the concurrency of the common Singleton design pattern and it memory profiling results. Singleton pattern is commonly used in coding and the objective of Singleton is to make sure that, only a single instance of the class is created. The common design with lazy initialization is present in most code. This is shown below (read with out the synchronized keyword).

This is fine as long as the code is executed by a single thread. If ever the code is executed by multiple threads, the 'check for null then act' part can result in multiple instances of the singleton class. If one thread A is checking the instance for null, returns true and it is moved out of processor for another thread B, B checks for null creates an instance. A comes back and creates another instance. So there will be 2 instances now as shown  in the run below. The class IamSingle has two instances without the synchronized keyword.

With the Synchronized keyword, the run profile is as follows. There is only one instance. 

This kind of bug can be difficult to reproduce as even getting the wrong scenario depends on the timing of the threads.

No comments: