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

时间:2011-03-08 19:29:00

标签: java queue

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

5 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:6)

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

/**
 * 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;
    }
}

答案 2 :(得分:3)

由链接哈希集支持的阻塞队列实现,用于可预测的迭代顺序和恒定时间添加,删除和包含操作:

There you go

答案 3 :(得分:-1)

您可以覆盖BlockingQueue<T>的任何实现的添加和放置方法,以首先检查该元素是否已在队列中,例如。

@Override
public boolean add(T elem) {
    if (contains(elem))
        return true;
    return super.add(elem);
}

答案 4 :(得分:-2)

class BlockingSet extends ArrayBlockingQueue<E> {
   /*Retain all other methods except put*/
   public void put(E o) throws InterruptedException {
      if (!this.contains(o)){
         super.put(o);
      }
   }
}