Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread safe singleton class

 
bjit babu
Greenhorn
Posts: 10
  • 0
  • 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: 4660
5
Linux Mac OS X VI Editor
  • 0
  • 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
  • 0
  • 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: 4838
34
Chrome Netbeans IDE Windows
  • 0
  • 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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic