use crate::listener::{EvictionListener, EvictionReason};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use fibre::mpsc;
pub(crate) type Notification<K, V> = (K, Arc<V>, EvictionReason);
pub(crate) struct Notifier<K: Send, V: Send + Sync> {
handle: JoinHandle<()>,
_sender: mpsc::BoundedSender<(K, Arc<V>, EvictionReason)>,
}
impl<K: Send, V: Send + Sync> Notifier<K, V> {
pub(crate) fn spawn(
listener: Arc<dyn EvictionListener<K, V>>,
) -> (Self, mpsc::BoundedSender<Notification<K, V>>)
where
K: Send + 'static,
V: Send + 'static,
{
const NOTIFICATION_CHANNEL_CAPACITY: usize = 128;
let (tx, rx): (
mpsc::BoundedSender<Notification<K, V>>,
mpsc::BoundedReceiver<Notification<K, V>>,
) = mpsc::bounded(NOTIFICATION_CHANNEL_CAPACITY);
let handle = thread::spawn(move || {
while let Ok((key, value, reason)) = rx.recv() {
listener.on_evict(key, value, reason);
}
});
let notifier = Self {
handle,
_sender: tx.clone(),
};
(notifier, tx)
}
pub(crate) fn stop(self) {
drop(self._sender);
}
}