In general, I want to block the provider of a blocking queue until the queue becomes empty, and then put a batch of elements into the queue.
I find a relative question here:
How to block until a BlockingQueue is empty?
However I'm still confused.
my current implementation is like (pseudo code):
BlockingQueue blockingQueue = new BlockingQueue();
// provider code
while (true) {
// wait until the blocking queue becomes empty
synchronized (blockingQueue) {
while (!blockingQueue.isEmpty()) {
blockingQueue.wait();
}
}
// put a batch of elements into blocking queue
List<Element> elementList = getSomeElements();
for (Element element : elementList) {
blockingQueue.put(element)
}
}
// consumer code
while (true) {
// take a element
blockingQueue.take();
// if the blocking queue becomes empty, notify the provider
synchronized (blockingQueue) {
if (blockingQueue.isEmpty()) {
blockingQueue.notify();
}
}
}
The code seems to be OK, but I still doubt that it is not thread-safe, and may lead to dead-lock condition.
Is my implementation thread-safe? Is there any better way to do this?