listener-holder
A thread-safe, lock-free read single-listener holder for Rust.
Use it when you have one optional callback/listener that may be set or cleared at runtime, and you want to notify it from any thread without repeating RwLock<Option<...>> boilerplate.
Requirements
- The listener type
Lmust implementSend + Sync. The holder is then safe to share across threads (e.g. viaArc<ListenerHolder<L>>).
Features
- Thread-safe:
ListenerHolder<L>isSend + SyncwhenL: Send + Sync. Safe to share viaArcacross threads. - Lock-free reads: Uses arc-swap internally; getting and notifying the listener do not take a lock. See docs/CONCURRENCY.md for comparison with
RwLock<Option<Arc<L>>>. - Single listener: Holds at most one listener; setting a new one replaces the previous.
- Simple API:
set(passNoneto clear),with_listener,get.
Usage
[]
= "0.1.1"
use ListenerHolder;
use Arc;
// Your listener type must be Send + Sync
;
let holder = new;
// Set listener
holder.set;
// Notify (only if listener is set)
holder.with_listener;
// Clear (pass None)
holder.set;
holder.with_listener; // no-op
// Get a clone of the current listener (e.g. to call from async code outside the lock)
if let Some = holder.get
When to use
- SDK or engine that exposes a single optional listener (e.g. connection listener, migration progress listener).
- You were about to write
RwLock<Option<Arc<dyn Listener>>>and want a ready-made type instead.
Panics
with_listenerdoes not panic by itself. If the closure you pass panics, the holder is left unchanged and other threads can continue to use it.- No other method panics under normal use.
License
MIT OR Apache-2.0