Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How to create thread-safe singleton in Java using double checked locking?

user-image
Question added by Mohd shahnawaz khan , Associate Project , Cognizant Technology Solution
Date Posted: 2013/09/01
George El Haddad
by George El Haddad , Software Engineer (Freelance) , Scientific Software Consultancy & Training

Double checked locking is not recomended in programming best practices mainly due to the fact that it can be unsafe and in most places it is considered an Anti-Pattern. The case where double checked locking becomes unsafe is documented on Wikipedia

Thread B notices that the shared variable has been initialized (or so it appears), and returns its value. Because thread B believes the value is already initialized, it does not acquire the lock. If B uses the object before all of the initialization done by A is seen by B (either because A has not finished initializing it or because some of the initialized values in the object have not yet percolated to the memory B uses (cache coherence)), the program will likely crash.

There are effectively3 correct ways to acheive the same result, but each one comes with different performance impacts.

  1. Synchronize the method: Correct but takes a big performance hit
  2. Use the volatile keyword for your instance: Correct and has performance gains but only to be used on Java1.5 and up (volatile implemenation on Java1.4 and below is broken)
  3. Use final wrapper: Correct and you can avoid using the volatile keyword

Performacne between using a final wrapper and volatile keyword may not be big, as always it is recommended to benchmark your options to suite your requirements.

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.