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

标签 java queue

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

最佳答案

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

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

关于仅包含唯一元素的 Java 阻塞队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5237283/

相关文章:

java - 解析器-如何读取文件?

google-app-engine - 在 App Engine 上排队电子邮件

java - 使用ArrayList(或更好的链接列表)编写自己的队列在技术上是否正确?[下面的java代码]

php - 没有模型 [App\Models\Match] 的查询结果

multithreading - 轮询无锁队列的最快无竞争方法是什么?

java - HTML 格式的 JLabel 上的古吉拉特语 Unicode 文本不起作用(方框)

java - "this"java 查询点

java - 如何在 Spring3 MVC 中设置与 MySQL 的 JDBC 连接?

java - 如何实现服务器关闭

java - 队列元素乱序排列,不按顺序排列