Design a thread-safe event dispatcher
PurestorageSoftware Engineer · OnsiteLast updated
This question evaluates understanding of concurrent programming and thread-safe design, including synchronization primitives, race-condition avoidance, listener lifecycle semantics, and event-delivery guarantees.
Problem: "Event fire" / event dispatcher with multithreading
Design an in-memory event system that supports registering listeners and firing events.
Core requirements
Implement an EventDispatcher (or EventBus) supporting:
subscribe(eventType, listener)unsubscribe(eventType, listener)fire(eventType, eventPayload)— invokes all listeners currently subscribed toeventType
Where listener is a callback/function.
Follow-ups (multithreading)
Assume subscribe, unsubscribe, and fire can be called concurrently from multiple threads.
Answer/discuss:
- What thread-safety guarantees will you provide? (e.g., “listeners registered before fire starts must be called exactly once”, handling concurrent unsubscribe, etc.)
- How will you avoid race conditions and deadlocks?
- How will you handle performance trade-offs under high read (fire) vs high write (subscribe/unsubscribe) workloads?
- Will
firebe synchronous (caller thread) or asynchronous (thread pool / queue)? How does that change your design?
You may state reasonable assumptions (e.g., per-event-type ordering is or isn’t required; at-least-once vs exactly-once delivery within a single process).
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.