问题 1:为什么在多线程的单例模式中我们需要两个空值检查?如果我们只使用外部检查怎么办?
if (instance == null) {
synchronized (ABC.class) {
// What if we remove this check?
if (instance == null) {
instance = new ABC();
}
}
问题2:以下有什么区别:
1:直接使用synchronized()里面的类名
public ABC getInstance() {
if (instance == null) {
// Difference here
synchronized (ABC.class) {
if (instance == null) {
instance = new ABC();
}
}
}
return instance;
}
2:在 synchronized() 中使用静态最终对象
private static final Object LOCK = new Object();
.
.
public ABC getInstance() {
if (instance == null) {
// Difference here
synchronized (LOCK) {
if (instance == null) {
instance = new ABC();
}
}
}
return instance;
}
3:在 synchronized() 中使用new Object( )
if (instance == null) {
// Difference here
synchronized (new Object()) {
if (instance == null) {
instance = new ABC();
}
}
}