From d484e7f731fe36832b4dd3ee690c1180bcc6117b Mon Sep 17 00:00:00 2001 From: Narendra Pathai Date: Fri, 5 Aug 2016 14:38:25 +0530 Subject: [PATCH] Documented singleton double check idiom, explaining the dynamics that happen on each step for better understanding. Did this due to a PR #475 --- .../iluwatar/singleton/ThreadSafeDoubleCheckLocking.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java index 50203609c..a8fd9648a 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java +++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java @@ -53,11 +53,20 @@ public final class ThreadSafeDoubleCheckLocking { public static ThreadSafeDoubleCheckLocking getInstance() { // local variable increases performance by 25 percent // Joshua Bloch "Effective Java, Second Edition", p. 283-284 + ThreadSafeDoubleCheckLocking result = instance; + // Check if singleton instance is initialized. If it is initialized then we can return the instance. if (result == null) { + // It is not initialized but we cannot be sure because some other thread might have initialized it + // in the meanwhile. So to make sure we need to lock on an object to get mutual exclusion. synchronized (ThreadSafeDoubleCheckLocking.class) { + // Again assign the instance to local variable to check if it was initialized by some other thread + // while current thread was blocked to enter the locked zone. If it was initialized then we can + // return the previously created instance just like the previous null check. result = instance; if (result == null) { + // The instance is still not initialized so we can safely (no other thread can enter this zone) + // create an instance and make it our singleton instance. instance = result = new ThreadSafeDoubleCheckLocking(); } }