Skip to content

Instantly share code, notes, and snippets.

@duyng2512
Last active October 8, 2022 15:23
Show Gist options
  • Save duyng2512/870d25336a980a3bc149c8d70dceed5a to your computer and use it in GitHub Desktop.
Save duyng2512/870d25336a980a3bc149c8d70dceed5a to your computer and use it in GitHub Desktop.
Event Loop Implementation
/*
Java implementation of Event Loop
Event Loop contain:
- List of event
- List of handler corresponding to each event data
*/
public final class EventLoop {
public static final class Event {
private final String key;
private final Object data;
public Event(String key, Object data) {
this.key = key;
this.data = data;
}
}
private final ConcurrentLinkedDeque <Event> events = new ConcurrentLinkedDeque <> ();
private final ConcurrentHashMap <String, Consumer <Object>> handlers = new➥ ConcurrentHashMap <> ();
public EventLoop on(String key, Consumer <Object> handler) {
handlers.put(key, handler);
return this;
}
public void dispatch(Event event) {
events.add(event);
}
public void stop() {
Thread.currentThread().interrupt();
}
public void run() {
while (!(events.isEmpty() && Thread.interrupted())) {
if (!events.isEmpty()) {
Event event = events.pop();
if (handlers.containsKey(event.key)) {
handlers.get(event.key).accept(event.data);
} else {
System.err.println("No handler for key " + event.key);
}
}
}
}
}
public static void main(String[] args) {
EventLoop eventLoop = new EventLoop();
new Thread(() -> {
for (int n = 0; n <6; n++) {
delay(1000);
eventLoop.dispatch(new EventLoop.Event("tick", n));
}
eventLoop.dispatch(new EventLoop.Event("stop", null));
}).start();
new Thread(() -> {
delay(2500);
eventLoop.dispatch(new EventLoop.Event("hello", "beautiful world"));
delay(800);
eventLoop.dispatch(new EventLoop.Event("hello", "beautiful universe"));
}).start();
eventLoop.dispatch(new EventLoop.Event("hello", "world!"));
eventLoop.dispatch(new EventLoop.Event("foo", "bar"));
eventLoop.on("hello", s -> System.out.println("hello " + s))
.on("tick", n -> System.out.println("tick #" + n))
.on("stop", v -> eventLoop.stop())
.run();
System.out.println("Bye!");
}
private static void delay(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
/*
hello world!
No handler for key foo
tick #0
tick #1
hello beautiful world
tick #2
hello beautiful universe
tick #3
tick #4
tick #5
Bye!
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment