java - 对单例模式使用双重检查锁定习惯用法是否最佳?

标签 java synchronization locking singleton

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

即:

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;

private static processManager singleton = null;

public synchronized static processManager getInsatnce() throws Exception {

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

    return singleton
 }

最佳答案

让 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();
    }
}

关于java - 对单例模式使用双重检查锁定习惯用法是否最佳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15526915/

相关文章:

api - 自定义 channel 播放列表与 Xtream 代码中的服务器同步

oracle - 我可以使用 Oracle PL/SQL 同时持有两个锁吗?

c++ - MCS锁实现的问题

java - Application Insights Log4j 按日志文件名筛选

java - Google map v2 - 用不同颜色绘制路线 - Android

java - 同步之前更新内存?

c - 如何同步多个appsink

kotlin - 一种有效的方法来锁定Kotlin中对特定资源的访问

java - 如何更有效地在 3 个不同的下拉菜单中输入日期、月份、年份

java - 当 JTable 中的数据更改时,ComboBox 不刷新