Java – multiple blocking queues, single consumer

I have multiple blockingqueues containing messages to send Is it possible to reduce the number of consumers in the queue? I don't want to loop queues and continue polling them (busy waiting). I don't want threads per queue Instead, I want a thread to wake up when a message is available on any queue

Solution

One trick you can do is queue up So what you do is a single block queue, all threads subscribe Then, when you put some content into a BlockingQueue, you will also put the blocking queue into the queue So you have something like this:

BlockingQueue<WorkItem> producers[] = new BlockingQueue<WorkItem>[NUM_PRODUCERS];
BlockingQueue<BlockingQueue<WorkItem>> producerProducer = new BlockingQueue<BlockingQueue<WorkItem>>();

Then when you get a new work project:

void addWorkItem(int queueIndex,WorkItem workItem) {
    assert queueIndex >= 0 && queueIndex < NUM_PRODUCERS : "Pick a valid number";
    //Note: You may want to make the two operations a single atomic operation
    producers[queueIndex].add(workItem);
    producerProducer.add(producers[queueIndex]);
}

Now your consumers can stop the producers I don't know how valuable this strategy is, but it does what you want

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>