0
votes

I have several parts of my application, that need to react to events triggered from somewhere else, so the first thing I thought about would be an event bus. These are the requirements I see:

  • The subscriber method should be typesafe
  • Implementing an interface (like Subscriber<T>) is not a problem
  • A subscriber should also receive any events of subtypes to the class it's registered to
  • Subscribers should be able to be registered with a priority (a simple int) or a default priority hardcoded somewhere in the code. When posting an event, the subscribers will be called in order. The events are mutable and some of their fields will change between subscribers
  • Each thread will have its own event bus and I will manually register all subscribers, so there's no need for static access
  • While receiving an event, it should be possible for a subscriber to unsubscribe without raising a ConcurrentModificationException

Bonus requirements I might need down the line:

  • Register new subscribers while handling events
  • Send events while receiving one. Those will be processed synchronously before proceeding with the current task
  • The option to "pool" events that currently have no subscriber and manually process them later (maybe by passing a Consumer).

Guava Eventbus probably does most of those things except for the priority. I can create a simple prioritized subscriber queue by using a TreeSet, but I'm not sure how to integrate it into Guava and I don't know if I want to depend on the whole library just for the bus.

Also, I might need a CopyOnWriteArrayList for the concurrent stuff (adding/removing while iterating), but I don't know about the performance implications. On that note, there probably won't be more than 10-15 subscribers at a time.

1

1 Answers

0
votes

Normal events are not designed to be mutable. You should stick with immutable data. Also subscribers are not intendet to be called within a certain order or to interact with another. For your usecase you could build different event busses for each priority. A subscriber could handover a copy of the modified event to the next priority bus.