AJ.
AJ.

Reputation: 2569

How to make a singleton class threadsafe?

I am implementing a singleton class in Java to make sure no more than one instance of the class is created.

Upvotes: 5

Views: 7238

Answers (6)

Michael Borgwardt
Michael Borgwardt

Reputation: 346457

Perhaps the best way is to use an enum with a single instance. This has the added benefit of being serializable and guaranteeing singleton-ness against serialization and reflection, which no "straightforward" Singleton implementation does (private? I have reflection, I scoff derisively at your access modifiers!). It's also very simple to implement:

public enum Singleton {
    INSTANCE;

    // fields and methods go here
}

Upvotes: 6

gustafc
gustafc

Reputation: 28885

The best way to make a singleton? Use an enum.

public enum Singleton {
    INSTANCE;
    public void foo(){ ... }
}

// Usage:
Singleton.INSTANCE.foo();

You get lots of help from the VM not only to avoid double instantiation, but it also helps you avoid deserialization corruption.

Upvotes: 11

jrockway
jrockway

Reputation: 42684

If you care about concurrency, you won't be using shared global state.

Upvotes: 0

enguerran
enguerran

Reputation: 3291

What about lazy instanciation: getInstance() returns the singleton or create it if it is the first call.

 public class MySingleton
 {
     private static MySingleton instance;

     private MySingleton()
     {
         // construct object . . .
     }

     // For lazy initialization
     public static synchronized MySingleton getInstance()
     {
         if (instance==null)
         {
             instance = new MySingleton();
         }
         return instance;
     }

     // Remainder of class definition . . .
 } 

Upvotes: 1

Tim Bender
Tim Bender

Reputation: 20442

public class Singleton {
  public static final Singleton INSTANCE = new Singleton();
  private Singleton() { ... }
}

Using a static instance variable is preferred to the internal "Holder" class. If you like, you can also make the static member private and provide a method for accessing it, but all that does is add another method call to the stack.

Upvotes: 2

Brian Rasmussen
Brian Rasmussen

Reputation: 116471

Singletons are not threadsafe per default. The common way to create a singleton is to have a factory method that handles creation of the one instance. That way you can control instance creation.

Upvotes: 0

Related Questions