对于单例模式使用双重检查锁定习语是否最佳?

Pec*_*tum 6 java singleton synchronization locking

对于单例模式,使用双重检查锁定习惯是否更好?还是同步方法?

即:

private static volatile ProcessManager singleton = null;

public static ProcessManager getInstance() throws Exception {

    if (singleton == null) {
       synchronized (MyClass.class) {
          if (singleton == null) {
               singleton = new ProcessManager();
         }
      }
   }
   return singleton;
Run Code Online (Sandbox Code Playgroud)

}

要么

private static processManager singleton = null;

public synchronized static processManager getInsatnce() throws Exception {

   if(singleton == null) {
            singleton = new processManager();
    }

    return singleton
 }
Run Code Online (Sandbox Code Playgroud)

LaG*_*ere 6

让ClassLoader为您完成工作:

    /*
     * This solution takes advantage of the Java memory model's guarantees about class initialization
     * to ensure thread safety. Each class can only be loaded once, and it will only be loaded when it
     * is needed. That means that the first time getInstance is called, mySingletonServiceLoader
     * will be loaded and instance will be created, and since this is controlled by ClassLoaders,
     * no additional synchronization is necessary.
     */
    public static DocumentService getInstance() {
        return mySingletonServiceLoader.INSTANCE;
    }

    private static class mySingletonServiceLoader {
         static DocumentService INSTANCE = new DocumentService();
    }
}
Run Code Online (Sandbox Code Playgroud)


pca*_*cao 0

基本上,你的第二个选择不会增加额外的保证。

您更频繁地检查,但它们之间仍然可能发生并发访问,因此,您减少了两个实例发生的概率,但没有消除它。