Skip to content

Commit d484e7f

Browse files
committed
Documented singleton double check idiom, explaining the dynamics that happen on each step for better understanding. Did this due to a PR iluwatar#475
1 parent 55028a4 commit d484e7f

File tree

1 file changed

+9
-0
lines changed

1 file changed

+9
-0
lines changed

singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,20 @@ private ThreadSafeDoubleCheckLocking() {
5353
public static ThreadSafeDoubleCheckLocking getInstance() {
5454
// local variable increases performance by 25 percent
5555
// Joshua Bloch "Effective Java, Second Edition", p. 283-284
56+
5657
ThreadSafeDoubleCheckLocking result = instance;
58+
// Check if singleton instance is initialized. If it is initialized then we can return the instance.
5759
if (result == null) {
60+
// It is not initialized but we cannot be sure because some other thread might have initialized it
61+
// in the meanwhile. So to make sure we need to lock on an object to get mutual exclusion.
5862
synchronized (ThreadSafeDoubleCheckLocking.class) {
63+
// Again assign the instance to local variable to check if it was initialized by some other thread
64+
// while current thread was blocked to enter the locked zone. If it was initialized then we can
65+
// return the previously created instance just like the previous null check.
5966
result = instance;
6067
if (result == null) {
68+
// The instance is still not initialized so we can safely (no other thread can enter this zone)
69+
// create an instance and make it our singleton instance.
6170
instance = result = new ThreadSafeDoubleCheckLocking();
6271
}
6372
}

0 commit comments

Comments
 (0)