Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread safe singleton class

 
bjit babu
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the best possible way to make a singleton class thread safe.
 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use a singleton class. Singletons are evil.

They can be thread safe if you make the data in them immutable.
 
Alexey Dubinin
Greenhorn
Posts: 2
IntelliJ IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simplest way is to use enum:

But remember that methods of this class should be thread safe.
 
Stephan van Hulst
Bartender
Pie
Posts: 5812
61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Singletons or enums aare no different from other classes when it comes to thread-safety.

Either synchronize them properly, or even better, make them immutable.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic