From 7522d15f7fef0a262fcfa32cd265ef9212f4b7f2 Mon Sep 17 00:00:00 2001 From: agent-smith Date: Mon, 17 Nov 2014 21:02:14 -0600 Subject: [PATCH] Update RightLazySingleton.java Double-check locking makes this perform better, so we don't take on the overhead of context switching threads every time getInstance() is called. --- .../singleton/lazy/RightLazySingleton.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) 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; }