问题描述
private static final Object lock = new Object();
private static volatile YourObject instance;
public static YourObject getInstance() {
YourObject r = instance; // <---------- This bit,why do we assign it here ?
if (r == null) {
synchronized (lock) { // What is the benefit of this lock in here
r = instance; // assuming instance is null which will pass the first if ( r == null,what do we assign it again ?? I don't get the idea of this step at all.
if (r == null) {
r = new YourObject();
instance = r;
}
}
}
return r;
}
我见过https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples,但其中的实现看起来像这样,没有两个分配。
public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
if(instance == null){
synchronized (ThreadSafeSingleton.class) {
if(instance == null){
instance = new ThreadSafeSingleton();
}
}
}
return instance;
}
解决方法
from IPython.display import HTML
html = anim.to_html5_video()
HTML(html)
在这里真正想要的是关于局部变量的推理更容易。另外,读取 YourObject r = instance; // <---------- This bit,why do we assign it here ?
可能不被优化程序合并的变量的开销。
volatile
此锁可以防止多个线程同时创建和分配 synchronized (lock) { // What is the benefit of this lock in here
的不同实例。
YourObject
r = instance; // assuming instance is null which will pass the first if ( r == null,what do we assign it again ?? I don't get the idea of this step at all.
可能在instance
校验的第一次读取与成功获取锁定之间已更改。
无论如何,不要使用双重检查锁定-这非常令人困惑,并且可能还有更好的方法。