java
50 lines · 7 steps
Building an annotation-driven EventBus in Java
A publish-subscribe hub that discovers handlers via reflection and dispatches events by type, synchronously or asynchronously.
Explained by
highlit
1public class EventBus {
2
3 private final Map<Class<?>, List<Subscriber>> subscribers = new ConcurrentHashMap<>();
4 private final Executor executor;
5
6 public EventBus(Executor executor) {
7 this.executor = executor;
8 }
9
10 public void register(Object listener) {
11 for (Method method : listener.getClass().getDeclaredMethods()) {
12 Subscribe annotation = method.getAnnotation(Subscribe.class);
13 if (annotation == null) {
14 continue;
15 }
16 if (method.getParameterCount() != 1) {
17 throw new IllegalArgumentException(
18 "@Subscribe method " + method + " must accept exactly one argument");
19 }
20 method.setAccessible(true);
21 Class<?> eventType = method.getParameterTypes()[0];
22 subscribers.computeIfAbsent(eventType, key -> new CopyOnWriteArrayList<>())
23 .add(new Subscriber(listener, method, annotation.async()));
24 }
25 }
26
27 public void post(Object event) {
28 List<Subscriber> targets = subscribers.get(event.getClass());
29 if (targets == null) {
30 return;
31 }
32 for (Subscriber subscriber : targets) {
33 if (subscriber.async) {
34 executor.execute(() -> subscriber.deliver(event));
35 } else {
36 subscriber.deliver(event);
37 }
38 }
39 }
40
41 private record Subscriber(Object target, Method method, boolean async) {
42 void deliver(Object event) {
43 try {
44 method.invoke(target, event);
45 } catch (ReflectiveOperationException e) {
46 throw new IllegalStateException("Failed to dispatch " + event, e);
47 }
48 }
49 }
50}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Reflection plus a marker annotation lets you wire handlers by convention instead of explicit registration.
- 2Keying subscribers by event class turns dispatch into a simple type lookup.
- 3Concurrent collections and an Executor let the bus stay thread-safe while offloading async delivery.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-an-annotation-driven-eventbus-in-java-explained-java-21ba/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.