简体   繁体   中英

How to make a singleton class threadsafe?

我在Java中实现一个单例类,以确保只创建了一个类的实例。

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.

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
}
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.

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 . . .
 } 

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.

如果您关心并发,则不会使用共享全局状态。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM