Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Singleton Pattern Thread Safe or Not

 
deepak carter
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All

below is small code for singleton pattern.




My question is is singleton pattern thread safe....??

 
deepika deepi
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
deepak Wrote: carter below is small code for singleton pattern.


The constructor is private and if single object is created, this is fine. If you use multiple threads you need to protect the getInstance() through synchronization other wise it might return two different instances of Singleton object
 
Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its not thread safe, multiple threads might compete for getInstance() and 2 threads might end up with totally different instances. One approach to solve this is by using double checked locking, but that has its own share of concerns like the Instance being available to a different thread even before the initialising thread has completed the initialisation i.e initializing the state.

In the book Effective Java this concept has been clearly explained.
 
Aditya Jha
Ranch Hand
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The easiest option for you would be to instantiate the singleton instance eagerly (on class load).

So, the line can be changed to
Also, you can then remove the if(instance == null) check from getInstance method, as it would be redundant (instance will never be null).

This is, of course, assuming, your design can afford to have this class eagerly instantiated. There are genuine cases where this is not a possibility.

Another option is to do away with hand-coded singleton completely, and rely on a container mechanism to ensure singularity. An example could be a singleton bean using Spring framework.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic