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() {
53
53
public static ThreadSafeDoubleCheckLocking getInstance () {
54
54
// local variable increases performance by 25 percent
55
55
// Joshua Bloch "Effective Java, Second Edition", p. 283-284
56
+
56
57
ThreadSafeDoubleCheckLocking result = instance ;
58
+ // Check if singleton instance is initialized. If it is initialized then we can return the instance.
57
59
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.
58
62
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.
59
66
result = instance ;
60
67
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.
61
70
instance = result = new ThreadSafeDoubleCheckLocking ();
62
71
}
63
72
}
You can’t perform that action at this time.
0 commit comments