File tree Expand file tree Collapse file tree 1 file changed +9
-0
lines changed
singleton/src/main/java/com/iluwatar/singleton Expand file tree Collapse file tree 1 file changed +9
-0
lines changed Original file line number Diff line number Diff 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 }
You can’t perform that action at this time.
0 commit comments