Compare commits

...

2 Commits

Author SHA1 Message Date
866a547114
Merge pull request 'Initialize the Default Event Bus Statically' (#23) from f/static-singleton-initialization into develop
Reviewed-on: https://git.kske.dev/kske/event-bus/pulls/23
Reviewed-by: delvh <leon@kske.dev>
2021-10-16 08:33:08 +02:00
33ebf0302b
Initialize the default event bus statically
The previous method that used double checked synchronization offers
little performance benefits over a plain static initialization.

Reported-by @harkle-the-cake
2021-10-16 08:32:28 +02:00

View File

@ -52,26 +52,18 @@ public final class EventBus {
*/ */
public static final int DEFAULT_PRIORITY = 100; public static final int DEFAULT_PRIORITY = 100;
private static volatile EventBus singletonInstance; private static final EventBus singletonInstance = new EventBus();
private static final Logger logger = System.getLogger(EventBus.class.getName()); private static final Logger logger = System.getLogger(EventBus.class.getName());
/** /**
* Produces a singleton instance of the event bus. It is lazily initialized on the first call. * Returns the default event bus, which is a statically initialized singleton instance.
* *
* @return a singleton instance of the event bus. * @return the default event bus
* @since 0.0.2 * @since 0.0.2
*/ */
public static EventBus getInstance() { public static EventBus getInstance() {
EventBus instance = singletonInstance; return 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<Class<?>, TreeSet<EventHandler>> bindings = private final Map<Class<?>, TreeSet<EventHandler>> bindings =