[英]Set that fires event when first element is added, or last one is removed
I've got an API that allows users to listen to network events.我有一个允许用户监听网络事件的 API。 I want to initiate a network connection when the first event listener is added, and disconnect when the last listener is removed.我想在添加第一个事件侦听器时启动网络连接,并在删除最后一个侦听器时断开连接。
Properties:属性:
What I've looked at so far:到目前为止我看过的内容:
CopyOnWriteArraySet
: thread-safe set that is optimized for reading more frequently than writing. CopyOnWriteArraySet
:线程安全集,针对读取比写入进行了优化。 There is no mechanism for running an operation when the first element is added or last one is removed.添加第一个元素或删除最后一个元素时,没有运行操作的机制。Phaser
: fires an event when the last element is removed, but not when the first one is added. Phaser
:当最后一个元素被移除时触发一个事件,但在第一个元素被添加时不会触发。 I guess I could use two Phasers
to achieve this behavior but it seems wasteful.我想我可以使用两个Phasers
来实现这种行为,但这似乎很浪费。Maybe ReadWriteLock is good for you?也许ReadWriteLock对你有好处?
A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. ReadWriteLock 维护一对关联的锁,一个用于只读操作,一个用于写入。 The read lock may be held simultaneously by multiple reader threads, so long as there are no writers.只要没有写者,读锁就可以被多个读者线程同时持有。 The write lock is exclusive.写锁是独占的。
Simple example (i use hashmap instead set):简单示例(我使用 hashmap 代替 set):
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class LockWrapper {
private final ReadWriteLock readWriteLock;
private final Map<Integer, Object> map;
private final EventSender sender;
public LockWrapper(EventSender eventSender) {
map = new HashMap<>();
readWriteLock = new ReentrantReadWriteLock();
sender = eventSender;
}
public void add(Object o) {
readWriteLock.writeLock().lock();
try {
if (map.isEmpty()) {
sender.send("First add");
}
map.put(o.hashCode(), o); // for example using hashcode for key
}
finally {
readWriteLock.writeLock().unlock();
}
}
public void remove(Object o) {
readWriteLock.writeLock().lock();
try {
map.remove(o.hashCode());
if (map.isEmpty()) {
sender.send("remove last");
}
}
finally {
readWriteLock.writeLock().unlock();
}
}
public Object read(int key) {
readWriteLock.readLock().lock();
try {
Object object = map.get(key);
}
finally {
readWriteLock.readLock().unlock();
}
return object;
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.