Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Design Patterns: Event Bus

DZone's Guide to

Design Patterns: Event Bus

Want to learn more about the Event Bus design pattern? Click here to check out example code for your projects.

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

Today, we are tackling something that is kind of new (and by that, I mean not mentioned in the GoF book), and that is the Event Bus.

Motivation

Imagine having a large scale application containing a lot of components interacting with each other, and you want a way to make your components communicate while maintaining loose coupling and separation of concerns principles, the Event Bus pattern can be a good solution for your problem.

The idea of an Event bus is actually quite similar to the Bus studied in Networking (Bus Topology). You have some kind of pipeline and computers connected to it, and whenever one of them sends a message, it’s dispatched to all of the others. Then, they decide if they want to consume the given message or just discard it.

Bus Networking Topology

At a component level, it’s quite similar: the computers are your application components, the message is the event or the data you want to communicate, and the pipeline is your EventBus object.

Implementation

There is no correct way to implement an Event Bus. I'm going to give a peak at two approaches here, finding other approaches is left as an exercise to the reader.

First Pattern

This one is kind of classic, as it relays on defining your EventBus interface (to force a given contract), implementing it the way you want, and defining a  Subscribable (another contract) to handle the Event(and yet another contract) consumption.

/**
 * interface describing a generic event, and it's associated meta data, it's this what's going to
 * get sent in the bus to be dispatched to intrested Subscribers
 *
 * @author chermehdi
 */
public interface Event<T> {

  /**
   * @returns the stored data associated with the event
   */
  T getData();
}
import java.util.Set;

/**
 * Description of a generic subscriber
 *
 * @author chermehdi
 */
public interface Subscribable {

  /**
   * Consume the events dispatched by the bus, events passed as parameter are can only be of type
   * declared by the supports() Set
   */
  void handle(Event<?> event);

  /**
   * describes the set of classes the subscribable object intends to handle
   */
  Set<Class<?>> supports();
}
import java.util.List;

/**
 * Description of the contract of a generic EventBus implementation, the library contains two main
 * version, Sync and Async event bus implementations, if you want to provide your own implementation
 * and stay compliant with the components of the library just implement this contract
 *
 * @author chermehdi
 */
public interface EventBus {

  /**
   * registers a new subscribable to this EventBus instance
   */
  void register(Subscribable subscribable);

  /**
   * send the given event in this EventBus implementation to be consumed by interested subscribers
   */
  void dispatch(Event<?> event);

  /**
   * get the list of all the subscribers associated with this EventBus instance
   */
  List<Subscribable> getSubscribers();
}


The Subscribable declares a method to handle a given type of objects and what type of objects it supports by defining the supports method .

The EventBus implementation holds a List of all the Subscribables and notifies all of them each time a new event comes to the  EventBusdispatch method .

Opting for this solution gives you compile time that checks the passed Subscribables, and also, it’s the more OO way of doing it, with no reflection magic needed, and as you can see, it can be easy to implement. The downside is that contract forcing thing — you always need a new class to handle a type of event, which might not be a problem at first, but as your project grows, you’re going to find it a little bit repetitive to create a class just to handle simple logic, such as logging or statistics.

Second Pattern

This pattern is inspired from Guava’s implementation, the EventBus implementation looks much simpler and easier to use. For every event consumer, you can just annotate a given method with @Subscribe and pass it an object of the type you want to consume (a single object/parameter), and you can register it as a message consumer by just calling eventBus.register(objectContainingTheMethod). To produce a new event, all you have to do is call eventBus.post(SomeObject) and all the interested consumers will be notified.

What happens if no consumer is found for a given object? Well, nothing really. In guava’s implementation, they call them DeadEvents; in my implementation, the call to post is just ignored .

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Simple implementation demonstrating how a guava EventBus works generally, without all the noise
 * of special cases handling, and special guava collections
 *
 * @author chermehdi
 */
public class EventBus {

  private Map<Class<?>, List<Invocation>> invocations;

  private String name;

  public EventBus(String name) {
    this.name = name;
    invocations = new ConcurrentHashMap<>();
  }

  public void post(Object object) {
    Class<?> clazz = object.getClass();
    if (invocations.containsKey(clazz)) {
      invocations.get(clazz).forEach(invocation -> invocation.invoke(object));
    }
  }

  public void register(Object object) {
    Class<?> currentClass = object.getClass();
    // we try to navigate the object tree back to object ot see if
    // there is any annotated @Subscribe classes
    while (currentClass != null) {
      List<Method> subscribeMethods = findSubscriptionMethods(currentClass);
      for (Method method : subscribeMethods) {
        // we know for sure that it has only one parameter
        Class<?> type = method.getParameterTypes()[0];
        if (invocations.containsKey(type)) {
          invocations.get(type).add(new Invocation(method, object));
        } else {
          List<Invocation> temp = new Vector<>();
          temp.add(new Invocation(method, object));
          invocations.put(type, temp);
        }
      }
      currentClass = currentClass.getSuperclass();
    }
  }

  private List<Method> findSubscriptionMethods(Class<?> type) {
    List<Method> subscribeMethods = Arrays.stream(type.getDeclaredMethods())
        .filter(method -> method.isAnnotationPresent(Subscribe.class))
        .collect(Collectors.toList());
    checkSubscriberMethods(subscribeMethods);
    return subscribeMethods;
  }

  private void checkSubscriberMethods(List<Method> subscribeMethods) {
    boolean hasMoreThanOneParameter = subscribeMethods.stream()
        .anyMatch(method -> method.getParameterCount() != 1);
    if (hasMoreThanOneParameter) {
      throw new IllegalArgumentException(
          "Method annotated with @Susbscribe has more than one parameter");
    }
  }

  public Map<Class<?>, List<Invocation>> getInvocations() {
    return invocations;
  }

  public String getName() {
    return name;
  }
}


You can see that opting for this solution requires less work on your part — nothing prevents you from naming your handler methods intention-revealing names rather than a general handle. And, you can define all your consumers on the same class. You just need to pass a different event type for each method.

Conclusion

Implementing an EventBus pattern can be beneficial for your code base as it helps loose coupling your classes and promotes a publish-subscribe pattern. It also help components interact without being aware of each other. Whichever implementation you choose to follow is a matter of taste and requirements.

All the code samples and implementation can be found in this repo.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
design pattens ,java ,Event Bus ,tutorial ,code

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}