Java阻塞队列仅包含唯一元素

ʞɔı*_*ɔıu 12 java queue

有点像"阻挡集".如何实现阻塞队列,其中忽略添加已在集合中的成员?

hor*_*rec 8

我写了这个类来解决类似的问题:

/**
 * Linked blocking queue with {@link #add(Object)} method, which adds only element, that is not already in the queue.
 */
public class SetBlockingQueue<T> extends LinkedBlockingQueue<T> {

    private Set<T> set = Collections.newSetFromMap(new ConcurrentHashMap<>());

    /**
     * Add only element, that is not already enqueued.
     * The method is synchronized, so that the duplicate elements can't get in during race condition.
     * @param t object to put in
     * @return true, if the queue was changed, false otherwise
     */
    @Override
    public synchronized boolean add(T t) {
        if (set.contains(t)) {
            return false;
        } else {
            set.add(t);
            return super.add(t);
        }
    }

    /**
     * Takes the element from the queue.
     * Note that no synchronization with {@link #add(Object)} is here, as we don't care about the element staying in the set longer needed.
     * @return taken element
     * @throws InterruptedException
     */
    @Override
    public T take() throws InterruptedException {
        T t = super.take();
        set.remove(t);
        return t;
    }
}
Run Code Online (Sandbox Code Playgroud)


Spi*_*nim 6

您可以创建一个组成BlockingQueue,Set和lock的新类.放入()时,在持有阻止get()运行的锁的同时对该集进行测试.当你得到()时,你从集合中删除该项目,以便将来可以再次放置().


How*_*ard 0

您可以重写任何实现的 add 和 put 方法,BlockingQueue<T>以首先检查该元素是否已在队列中,例如

@Override
public boolean add(T elem) {
    if (contains(elem))
        return true;
    return super.add(elem);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果“最佳”包括正确,那么此实现将失败,因为它是竞争条件。 (12认同)