aspose file tools*
The moose likes Beginning Java and the fly likes Singleton Pattern Thread Safe or Not Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Singleton Pattern Thread Safe or Not" Watch "Singleton Pattern Thread Safe or Not" New topic
Author

Singleton Pattern Thread Safe or Not

deepak carter
Ranch Hand

Joined: Feb 19, 2011
Posts: 165
Hi All

below is small code for singleton pattern.




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

deepika deepi
Ranch Hand

Joined: Jan 23, 2012
Posts: 199
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

Joined: Sep 08, 2007
Posts: 3070
    
  33

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.


Mohamed Sanaulla | My Blog
Aditya Jha
Ranch Hand

Joined: Aug 25, 2003
Posts: 227

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Singleton Pattern Thread Safe or Not