我指的是维基百科上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()被调用的时刻.因此,该解决方案是线程安全的,无需特殊的语言结构(即volatile或synchronized).
但是,2个线程是否有可能getInstance()同时调用,这会导致创建两个单例实例?synchronized在这里使用不安全吗?如果是,那么它应该在代码中使用的位置?