在 Singleton 中循环而不是 if 块
While loop in Singleton instead of if block
我在使用 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
可能会影响多线程环境中的单例创建?
没有必要使用 while
循环。
每个循环只会执行零次或一次,所以它们等同于 if.
我在使用 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
可能会影响多线程环境中的单例创建?
没有必要使用 while
循环。
每个循环只会执行零次或一次,所以它们等同于 if.