From dbb816c6cb1b2c00142df46700b94910d7701b0d Mon Sep 17 00:00:00 2001 From: kske Date: Thu, 24 Sep 2020 17:41:08 +0200 Subject: [PATCH] Add double checked synchronization to EventBus instance initializer --- src/main/java/dev/kske/eventbus/EventBus.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/java/dev/kske/eventbus/EventBus.java b/src/main/java/dev/kske/eventbus/EventBus.java index 4905889..98114fc 100644 --- a/src/main/java/dev/kske/eventbus/EventBus.java +++ b/src/main/java/dev/kske/eventbus/EventBus.java @@ -19,7 +19,7 @@ import java.util.concurrent.ConcurrentHashMap; */ public final class EventBus { - private static EventBus singletonInstance; + private static volatile EventBus singletonInstance; private static final Logger logger = System.getLogger(EventBus.class.getName()); @@ -30,11 +30,15 @@ public final class EventBus { * @since 0.0.2 */ public static EventBus getInstance() { - if (singletonInstance == null) { - logger.log(Level.DEBUG, "Initializing singleton event bus instance"); - singletonInstance = new EventBus(); - } - return singletonInstance; + EventBus instance = singletonInstance; + if (instance == null) + synchronized (EventBus.class) { + if ((instance = singletonInstance) == null) { + logger.log(Level.DEBUG, "Initializing singleton event bus instance"); + instance = singletonInstance = new EventBus(); + } + } + return instance; } private final Map, TreeSet> bindings