It's not a secret anymore!
The moose likes Java in General and the fly likes thread safe singleton class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "thread safe singleton class" Watch "thread safe singleton class" New topic

thread safe singleton class

bjit babu

Joined: Mar 25, 2010
Posts: 10
what is the best possible way to make a singleton class thread safe.
Pat Farrell

Joined: Aug 11, 2007
Posts: 4659

Don't use a singleton class. Singletons are evil.

They can be thread safe if you make the data in them immutable.
Alexey Dubinin

Joined: Mar 23, 2010
Posts: 2

The simplest way is to use enum:

But remember that methods of this class should be thread safe.
Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4621

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.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
I agree. Here's the link:
subject: thread safe singleton class
It's not a secret anymore!