singleton design pattern with thread safe
I read the reason for synchronize the new instance creation is two threads can access getInstance same time and find that _instance is null and create two instances of Singleton class. So in order to eliminate that we synchronized it. But again how come a double-checked locking method introduce again check whether the instance is null inside the Synchronized block. Does this necessary? Once a code block is synchronized it already thread safe know?
public class Singleton {
private static Singleton _instance = null;
private Singleton() { }
public static Singleton getInstance() {
if (_instance == null) {
synchronized (Singleton.class) {
_instance = new Singleton(); // why need to again check null
}
}
return _instance;
}
}
The synchronized
block will be executed sequentially (ie, one thread at a time), but that's not enough, because the second call to _instance = new Singleton()
might override the first one.
It's a plausible scenario if one context-switch takes place immediately after the first thread evaluates the _instance == null
expression, and no other context-switch takes place until another thread evaluates the _instance == null
expression.
Therefore, once inside the synchronized
block, the current thread has to make sure that _instance
is still null
before setting it to a new Singleton()
.
上一篇: 比较枚举的最好方法
下一篇: 单线程设计模式与线程安全