我有一个我不理解的代码片段,我将强调一下让我困惑的部分。
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;
}发布于 2020-10-28 05:27:35
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. 在第一次读取null检查和成功获取锁之间,instance可能已更改。
无论如何,不要使用双重检查锁定-这非常令人困惑,而且可能有更好的方法。
https://stackoverflow.com/questions/64562998
复制相似问题