Factory方法创建单例实例

Sha*_*ire 5 java multithreading


我在静态工厂方法中编写了下面的代码来返回DefaultCache的单个实例.

public static ICache getInstance() {
   if (cacheInstance == null) {
      synchronized (ICache.class) {
         if (cacheInstance == null) {
            cacheInstance = new DefaultCache();
         }
      }
   }
   return cacheInstance;
}
Run Code Online (Sandbox Code Playgroud)

我们真的需要在synchronized块内对cacheInstance进行第二次空检查吗?

Pet*_*rey 6

您需要进行第二次检查,因为在您尝试获取锁定时,该值可能已由另一个线程设置.事实上,在同步块内部之前,您没有此值的安全视图.它可以在任何时间之前由另一个线程设置.

最简单的懒惰单身是使用枚举

public enum DefaultCache implements ICache {
     INSTANCE
}
Run Code Online (Sandbox Code Playgroud)

我假设你没有这样做,所以你可以改变实现.

顺便说一句:我建议你尽可能使用无状态单例,尽可能使用依赖注入所有有状态对象.


mur*_*uga -1

使用私有构造函数来避免所有这些检查。

class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {
    }

    public static final Singleton getInstance() {
        return instance;
    }
}
Run Code Online (Sandbox Code Playgroud)