2015-01-05

Event Bus For Java

An event bus is a software library used for objects to message each other indirectly. Some objects register with the bus to be notified when certain events of interest occur. And some post events on the bus. The bus itself notifies each of the registrants when the event is posted. So the registrant objects and the event-source objects need not know about each other directly. Each may join or depart the bus at any time. You can think of it as a "pub-sub" publish-subscribe system, but internal to a single app.

The word ‘bus’ plays off the idea of a computer bus where hardware components in a computer system communicate with one another.

An event bus is an alternative to the Observer pattern, as seen in Swing and other Java libraries where called event listeners.

Guava EventBus


The most commonly known event bus for Java is probably the EventBus library included as part of Google Guava. Guava is filled with many handy pieces of goodness.

Unfortunately, the Guava EventBus library inexplicably holds strong references to the registered objects. That means the calling programmer must take care to deregister each object when reaching its end-of-life. Otherwise, a memory leak occurs as the Guava EventBus will hold the object’s reference indefinitely even after the programmer intended the object to be garbage-collected. If weak references were held by the bus, then terminating objects could proceed to garbage collection while the bus detected and deregistered any such disappeared (garbage-collected) objects.

Also, a minor issue, Guava EventBus supports asynchronous dispatch through a subclass rather than by default.

On the upside, we can expect Google’s team to thoroughly test and debug their work.

Read this article showing usage of Guava EventBus.

MBassador & Mycila


A couple years ago a pair of open-source event bus projects energetically burst upon the Java scene:
Both of these projects support weak references and async dispatch.

SimpleBus & EventBus


The inventor of MBassador wrote a comparison of a few older Java-based event bus projects (no mention of Mycila). His more modern library is reportedly much faster and uses less memory than its predecessors including Guava EventBus.

The other predecessors include:
  • SimpleBus
  • EventBus by Michael Bushe (apparently defunct)

GreenRobot EventBus


Recently I ran across GreenRobot EventBus project, a publish/subscribe event bus optimized for Android. I have not yet tried it.

Caveat: As of 2015-02, this library does not use weak references. This open issue # 57 requests such a feature. The main developer seems to be in favor. But not yet implemented.