Reputation: 1385
Regarding a previous question I raised,
public static Singleton getInstanceDC() {
if (_instance == null) { // Single Checked (1)
synchronized (Singleton.class) {
if (_instance == null) { // Double checked (2)
_instance = new Singleton();
}
}
}
return _instance;
}
Why should I use the second instance null check condition. What possible effect could it have?
Upvotes: 1
Views: 52
Reputation: 120516
Let's number lines so we can see how threads might interleave operations.
if (_instance == null) { // L1
synchronized (Singleton.class) { // L2
if (_instance == null) { // L3
_instance = new Singleton();// L4
}
}
}
Let's consider an interleaving without the check on L3.
_instance
is null
_instance
is null
Two instances were created of Singleton
. Each thread returns its own instance.
With the check at L3, step 8 doesn't happen because at step 7 thread 2's view of _instance
was synced with thread 1's, so only one instance of Singleton
is created.
Upvotes: 4