CopyOnWriteArraySet Snapshot Listener Registry
Deduplicate event handlers with CopyOnWriteArraySet and iterate over a point-in-time snapshot so listeners can unsubscribe mid-dispatch safely.
Code
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Consumer;
public class SnapshotEventBus {
record NamedListener(String id, boolean oneShot) implements Consumer<String> {
@Override
public void accept(String event) {
System.out.println(id + " handled: " + event);
}
}
public static void main(String[] args) {
CopyOnWriteArraySet<NamedListener> listeners = new CopyOnWriteArraySet<>();
NamedListener audit = new NamedListener("audit", false);
NamedListener welcome = new NamedListener("welcome", true);
// Set semantics prevent duplicate registrations of the same handler
System.out.println("added audit 1st: " + listeners.add(audit));
System.out.println("added audit 2nd: " + listeners.add(audit));
listeners.add(welcome);
// Iteration uses a snapshot array, so removing inside the loop never throws CME
for (NamedListener listener : listeners) {
listener.accept("user.signup");
if (listener.oneShot()) {
listeners.remove(listener);
}
}
System.out.println("remaining count: " + listeners.size());
for (NamedListener listener : listeners) {
listener.accept("user.login");
}
}
}Annotated execution — CopyOnWriteArraySet Snapshot Listener Registry
CopyOnWriteArraySet Snapshot Listener Registry is built around the classes SnapshotEventBus and NamedListener and the functions accept and main.
A single loop drives the file — for (NamedListener listener : listeners).
Watch out for
- Zero project setup files need updating before executing this code.
Using it
Signature: public void accept(String event)
The run prints added audit 1st:, added audit 2nd:, remaining count: — each prefix names the step that produced it.
The sequence accept lives in main; running the file triggers it.
Key statements
CopyOnWriteArraySet<NamedListener> listeners = new CopyOnWriteArraySet<>();
NamedListener welcome = new NamedListener("welcome", true);
NamedListener audit = new NamedListener("audit", false);
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does CopyOnWriteArraySet Snapshot Listener Registry print when run?
- Invoke the file as-is — the `added audit 1st:`, `added audit 2nd:`, `remaining count:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.