Add double checked synchronization to EventBus instance initializer

This commit is contained in:
Kai S. K. Engelbart 2020-09-24 17:41:08 +02:00
parent 603a838640
commit dbb816c6cb
Signed by: kske
GPG Key ID: 8BEB13EC5DF7EF13

View File

@ -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) {
EventBus instance = singletonInstance;
if (instance == null)
synchronized (EventBus.class) {
if ((instance = singletonInstance) == null) {
logger.log(Level.DEBUG, "Initializing singleton event bus instance");
singletonInstance = new EventBus();
instance = singletonInstance = new EventBus();
}
return singletonInstance;
}
return instance;
}
private final Map<Class<? extends IEvent>, TreeSet<EventHandler>> bindings