How do I give priority to Consumers when using a LinkedBlockingQueue?

I am using a LinkedBlockingQueue together with the producer/consumer pattern to buffer tasks. To add tasks to the queue I use the method for my producers: Queue.put(Object); To take a task form my queue I use for my consumers: Queue.take(Object);

I found in the Java api that both these methods will block until they the queue becomes available. My problem is: I know for a fact that there are more producers of tasks in my system then consumers. And all my tasks need to be processed. So I need my consumers, when blocked, to have priority over the producers to get the queue.

Is their a way to do this without changing the methods of LinkedBlockingQueue to much?


LinkedBlockingQueue uses two ReenterantLocks lock.

private final ReentrantLock putLock = new ReentrantLock();

private final ReentrantLock takeLock = new ReentrantLock();

Since both the locks are seperate and put and take aquires seperate locks for carrying out their operating blocking one operation would not impact other operation.

Cheers !!


There is no need to prioritize consumers over producers, because they block under entirely different conditions: if the producer is blocked because the queue is full, then the consumers won't be blocked as a result of the queue being empty.

For example, producer1 has a blocked put call because the queue is full. Consumer1 then executes take , which proceeds as normal because the queue is not empty (unless your queue has a capacity of 0, which would be silly) - the consumer doesn't know or care that a producer's put call is blocked, all it cares about is that the queue is not empty.


The producers being blocked doesn't block consumers due to multiple independent locks.

take( states:

Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

put( states:

Inserts the specified element at the tail of this queue, waiting if necessary for space to become available

If there is no space, then put will block but take won't get blocked as it's by design waiting only if the queue is empty, obviously not the case here.


Original comment:

As far as I know, this queue, by design, won't block consumers even if producers are blocked due to the queue being full.

链接地址: http://www.djcxy.com/p/21512.html

上一篇: 声明Actor状态变量是可变的

下一篇: 如何在使用LinkedBlockingQueue时优先考虑消费者?