相关疑难解决方法(0)

793
推荐指数
17
解决办法
30万
查看次数

维基百科的单例模式实现

我指的是维基百科上Bill Pugh的Singleton Pattern解决方案:

public class Singleton
{

    // Private constructor prevents instantiation from other classes

    private Singleton() {}

     /**
    * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
    * or the first access to SingletonHolder.INSTANCE, not before.
    */

    private static class SingletonHolder 
    { 

        private static final Singleton INSTANCE = new Singleton();
    }

   public static Singleton getInstance()
   {

       return SingletonHolder.INSTANCE;
   }

}
Run Code Online (Sandbox Code Playgroud)

他们在这里提到:

内部类之前没有引用(因此不会被类加载器加载),而不是getInstance()被调用的时刻.因此,该解决方案是线程安全的,无需特殊的语言结构(即volatilesynchronized).

但是,2个线程是否有可能getInstance()同时调用,这会导致创建两个单例实例?synchronized在这里使用不安全吗?如果是,那么它应该在代码中使用的位置?

java singleton design-patterns

6
推荐指数
2
解决办法
1483
查看次数

标签 统计

design-patterns ×2

java ×2

singleton ×2