• 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
Posts: 6311
77
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic