我了解了 Bill Pugh 在 Java 中实现 Singleton 设计模式的方法。
我对此有疑虑。如果我有任何错误,请纠正我。
请考虑以下 Bill Pugh 的代码:
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 {
public static final Singleton INSTANCE = new Singleton(); // Line 10
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE; // Line 14
}
}
考虑“Thread-1”已调用“return SingletonHolder.INSTANCE;”首次乘坐14号线。现在 Singleton 类将在第 10 行实例化。
在实例化完成之前,假设“Thread-1”被另一个线程“Thread-2”抢占。当“Thread-2”调用“return SingletonHolder.INSTANCE;”时14号线,
它会返回部分构造的对象吗?
如果它返回一个部分构造的对象,这种情况将是“乱序写入”。请告诉我我对上述案例的看法是否正确,并分享您的想法。 另请告诉我是否可以通过其他方式克服这种情况。
最佳答案
Will it return partially constructed Object?
答案是否。
return SingletonHolder.INSTANCE;
当第一个线程调用此行时,SingletonHolder
类将由 ClassLoader 加载。现在classloading is thread-safe process ,然后以线程安全的方式初始化类 SingletonHolder
中的静态变量。因此,完全创建的Singleton
的引用将被分配给INSTANCE
,然后控制权才会返回到调用者线程。在此之前,所有其他线程将等待类加载过程完成。因此,不完整创建的对象将不会被返回。
关于java - Bill Pugh 实现 Singleton 的方法导致 "Out-of-order Write"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18714620/