如何包装 ConcurrentSkipListSet 以线程安全的方式保持最新值的固定容量?
How to wrap ConcurrentSkipListSet to keep a fixed capacity of the latest values in a thread-safe way?
我想换行 ConcurrentSkipListSet to keep a fixed capacity of the latest (according to Comparator) 值:
private int capacity = 100;
// using Integer just for an illustration
private ConcurrentSkipListSet<Integer> intSet = new ConcurrentSkipListSet<>();
因此,我这样实现put()
:
// This method should be atomic.
public void put(int value) {
intSet.add(value);
if (intSet.size() > capacity)
intSet.pollFirst();
}
但是,这个 put()
不是线程安全的。
注:无其他变异方法。当然,我需要 "read-only" 方法,例如 getLast()
或 getBefore(Integer value)
.
How to wrap ConcurrentSkipListSet to keep a fixed capacity of the latest values in a thread-safe way?
您不太可能能够做到这一点并获得 ConcurrentSkipListSet
的并发优势。到那时,你还不如直接使用Collections.synchronizedNavigableSet(TreeSet)
,此时你可以直接写
synchronized (set) {
set.add(value);
if (set.size() > cap) {
set.pollFirst();
}
}
我想换行 ConcurrentSkipListSet to keep a fixed capacity of the latest (according to Comparator) 值:
private int capacity = 100;
// using Integer just for an illustration
private ConcurrentSkipListSet<Integer> intSet = new ConcurrentSkipListSet<>();
因此,我这样实现put()
:
// This method should be atomic.
public void put(int value) {
intSet.add(value);
if (intSet.size() > capacity)
intSet.pollFirst();
}
但是,这个 put()
不是线程安全的。
注:无其他变异方法。当然,我需要 "read-only" 方法,例如 getLast()
或 getBefore(Integer value)
.
How to wrap ConcurrentSkipListSet to keep a fixed capacity of the latest values in a thread-safe way?
您不太可能能够做到这一点并获得 ConcurrentSkipListSet
的并发优势。到那时,你还不如直接使用Collections.synchronizedNavigableSet(TreeSet)
,此时你可以直接写
synchronized (set) {
set.add(value);
if (set.size() > cap) {
set.pollFirst();
}
}