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
python
import time from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path
Parallel file downloads with a thread pool
concurrency
thread-pool
streaming-io
Intermediate
8 steps
java
package com.example.payments.config; import com.stripe.StripeClient; import org.springframework.beans.factory.annotation.Value;
Swapping payment gateways by profile in Spring
dependency-injection
profiles
configuration
Intermediate
6 steps
go
package validate import ( "fmt"
Struct validation with reflection in Go
reflection
struct-tags
validation
Intermediate
7 steps
php
final class TokenBucketLimiter { private float $tokens; private float $lastRefill;
How a token bucket rate limiter works
rate-limiting
token-bucket
throttling
Intermediate
7 steps
java
public class OrderSerializer { private final ObjectMapper mapper;
Configuring a reusable Jackson ObjectMapper
serialization
json
builder-pattern
Intermediate
8 steps
java
package com.example.maintenance; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
How a scheduled cleanup job runs in Spring
scheduling
cron
transactions
Intermediate
6 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.