【发布时间】:2020-07-10 15:22:57
【问题描述】:
我在使用 DoubleLocking 创建单例时遇到了以下代码
public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
while(instance == null){
synchronized (ThreadSafeSingleton.class) {
while(instance == null){
instance = new ThreadSafeSingleton();
}
}
}
return instance;
}
使用while loop 而不是通常的if block 有什么意义?是不是因为某些JMM issues 可能会影响多线程环境中的单例创建?
【问题讨论】:
-
那是不必要的。它只会循环一次,所以相当于if。
-
关于双重检查锁定的问题是它很难正确处理(甚至 Josh Bloch 在 Effective Java 3rd 的第一次印刷中就弄错了Ed),所以人们会做……奇怪的事情,“以防万一”。
标签: java multithreading singleton