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.