• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Singleton Pattern Thread Safe or Not

 
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All

below is small code for singleton pattern.




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

 
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 3225
34
IntelliJ IDE Oracle Spring Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 227
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic