Summary
I have a single consumer, multiple producer problem where each producer puts its data on a separate queue (because their data types are different), and the producers are all on their own threads.
The consumer, in a loop, will pull items from the producer queues based on their priorities, and then when all the queues are empty, it should go to sleep until more data is produced.
I don't know the best (error-free and fastest) way to put the consumer to sleep and then later to wake it up.
Current Code
Currently I'm using a simple semaphore. Every time new data has been produced the producer calls:
void produce(Data data) {
queue.add(data);
semaphore.release();
}
And the consumer:
while (!Thread.currentThread().isInterrupted()) {
consumeQueues();
semaphore.tryAcquire(time, TimeUnit.SECONDS);
semaphore.drainPermits();
}
Current Thoughts
Use an empty selector
, have the consumer call selector.select()
and the producers call selector.wakeup()
.
Rewrite all of the produced values and switch to a priority queue. Would be a lot of work and I'm not even sure I could get exactly the same behavior as I have now without losing speed.
Using the lock
/conditional
approach and calling conditional.await()
and conditional.signal()
. I'm worried about adding a lot of code and slowing things down with the added lock acquisitions (performance sensitive code).
Preferably I'd just use a static AtomicBoolean
that the producers could lazily set to true when data is available, but AtomicBoolean
don't have a block-until-true method.