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/

相关文章:

java - 将类路径目录/文件 Autowiring 到 Bean

java - 从 JSON moxy 输出重命名 "type"

java - 我正在尝试用java创建一个三角形

linux - Linux 中内核空间和用户空间之间的原子行为?

java - 如何使用 Java 检测同步冲突

java - 同步到要实例化的对象

Java 8 : Create tuples from Java List

java - 同步 Java Visualizer 音频和视频

NHibernate + ViewModel +MVC + 乐观锁

java - 我需要什么 Hibernate LockMode 来读取和更新对象,同时防止其他人这样做?