简体   繁体   中英

BlockingQueue like container that doesn't allow duplicates

I want a thread-safe container that blocks the caller until an item becomes available. Items will be added at a rate of 1000s per second to this container but will not be drained the same rate. Therefore, I want the container to disallow duplicates. I wrote a very simple wrapper around LinkedBlockingQueue but soon realized that I've recreated the classic producer-consumer deadlock. This is what I had written:

public class ActivityListener {
    private final BlockingQueue<ID> activeItems = new LinkedBlockingQueue<>();

    public synchronized ID take() throws InterruptedException {
        return activeItems.take();
    }

    public synchronized void registerActivity(final ID item) {
        if (!activeItems.contains(item)) {
            activeItems.add(item);
        }
    }

    public synchronized boolean isItemActive(final ID item) {
        return activeItems.contains(item);
    }
}

I could not find an established solution to my problem and would appreciate any help.

Override the add() and put() methods of any implementation of BlockingQueue to check first if the element is already within the queue.

Something like -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM