有界,自动丢弃,非阻塞,并发收集 [英] Bounded, auto-discarding, non-blocking, concurrent collection
本文介绍了有界,自动丢弃,非阻塞,并发收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在寻找一个集合:
- 是
Deque
/列表
- 即支持在顶部插入元素(最新项目到顶部) -deque.addFirst(..)
/list.add(0,..)
。它可以是Queue
,但是迭代顺序应该是相反的 - 即最近添加的项目应该优先。 - - 即限制为20个项目
- 在达到容量时自动舍弃最旧的项目(位于底部的项目,最先添加)
- 非阻塞 - 如果deque是空的,检索不应该阻塞。
- 并发 - 多个线程应该能够对其进行操作
- is a
Deque
/List
- i.e. supports inserting elements at "the top" (newest items go to the top) -deque.addFirst(..)
/list.add(0, ..)
. It could be aQueue
, but the iteration order should be reverse - i.e. the most recently added items should come first. - is bounded - i.e. has a limit of 20 items
- auto-discards the oldest items (those "at the bottom", added first) when the capacity is reached
- non-blocking - if the deque is empty, retrievals should not block. It should also not block / return false / null / throw exception is the deque is full.
- concurrent - multiple threads should be able to operate on it
我可以使用 LinkedBlockingDeque
并将其包装到我的自定义集合中, code>操作检查大小并丢弃最后一个项目。
I can take LinkedBlockingDeque
and wrap it into my custom collection that, on add
operations checks the size and discards the last item(s). Is there a better option?
推荐答案
我做了这个简单的实现:
I made this simple imeplementation:
public class AutoDiscardingDeque<E> extends LinkedBlockingDeque<E> {
public AutoDiscardingDeque() {
super();
}
public AutoDiscardingDeque(int capacity) {
super(capacity);
}
@Override
public synchronized boolean offerFirst(E e) {
if (remainingCapacity() == 0) {
removeLast();
}
super.offerFirst(e);
return true;
}
}
对于我的需要这足够了,不同于 addFirst
/ offerFirst
的文档方法仍然遵循阻塞deque的语义。
For my needs this suffices, but it should be well-documented methods different than addFirst
/ offerFirst
are still following the semantics of a blocking deque.
这篇关于有界,自动丢弃,非阻塞,并发收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文