Question 1: Why in singleton pattern for multi-threading we need two null checks? What if we use only the outer check?
if (instance == null) {
synchronized (ABC.class) {
// What if we remove this check?
if (instance == null) {
instance = new ABC();
}
}
Question 2: What's the difference between the following:
1: Using directly the class name inside synchronized()
public ABC getInstance() {
if (instance == null) {
// Difference here
synchronized (ABC.class) {
if (instance == null) {
instance = new ABC();
}
}
}
return instance;
}
2: Using a static final Object inside 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: Using new Object() inside synchronized()
if (instance == null) {
// Difference here
synchronized (new Object()) {
if (instance == null) {
instance = new ABC();
}
}
}