diff --git a/src/main/java/org/abqjug/javapatterns/singleton/lazy/RightLazySingleton.java b/src/main/java/org/abqjug/javapatterns/singleton/lazy/RightLazySingleton.java index f6c2d86..f87b323 100644 --- a/src/main/java/org/abqjug/javapatterns/singleton/lazy/RightLazySingleton.java +++ b/src/main/java/org/abqjug/javapatterns/singleton/lazy/RightLazySingleton.java @@ -11,9 +11,17 @@ public class RightLazySingleton { private RightLazySingleton() { } - public static synchronized RightLazySingleton getInstance() { + public static RightLazySingleton getInstance() { if (instance == null) { - instance = new RightLazySingleton(); + // Only synchronize once (i.e. we don't want to context switch every time getInstance is called!) + synchronized(RightLazySingleton.class) { + // Need the 2nd null check in case 1 or more threads were waiting for the lock, while + // the first thread assigned the instance. So, if 1 or more threads got past the first + // null check, they will not get past the 2nd when the first thread releases the lock. + if (instance == null) { + instance = new RightLazySingleton(); + } + } } return instance; }