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
public final class Ulid { private static final char[] ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ".toCharArray(); private static final SecureRandom RANDOM = new SecureRandom();
How to generate a ULID in Java
base32-encoding
bit-manipulation
identifiers
Intermediate
8 steps
go
package handler type flightResult struct { status int
Deduping in-flight requests in Gin
middleware
concurrency
deduplication
Advanced
9 steps
java
@RestController @RequestMapping("/api/reports") public class ReportController {
Header-driven endpoints in a Spring controller
rest api
request headers
dependency injection
Intermediate
7 steps
go
package middleware import ( "net/http"
Per-IP write rate limiting in Gin
rate-limiting
middleware
concurrency
Intermediate
8 steps
python
import asyncio from dataclasses import dataclass import aiohttp
Bounded-concurrency HTTP fetching with asyncio
async
concurrency
semaphore
Intermediate
8 steps
rust
use std::sync::Arc; use axum::{ extract::{Multipart, State}, http::StatusCode,
Throttling file uploads in Axum with a Semaphore
concurrency
backpressure
multipart
Advanced
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.