Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Does LinkedBlockingQueue take into account order of consumers?

I have 3 threads: 2 consumers, ConsumerA and ConsumerB, and a Producer.

I also have a LinkedBlockingQueue queue

At t=1: ConsumerA calls queue.take()

At t=2: ConsumerB calls queue.take()

At t=3: Producer calls queue.put(foo)

Is it guaranteed that ConsumerA receives foo before ConsumerB? In other words, the order in which the consumers invokes take() is the order in which each is notified?

If not, is there an alternative data structure that will give higher priority based on order?

like image 826
zer0stimulus Avatar asked Jul 26 '10 21:07

zer0stimulus


1 Answers

From looking at the source code, it's not guaranteed. There's a guarded block mechanism in place with the waking up of one thread at random, depending on how the scheduler feels.

 notEmpty.signal(); // propagate to a non-interrupted thread

Full code: http://kickjava.com/src/java/util/concurrent/LinkedBlockingQueue.java.htm

Edit: just looked again at ReenterantLock and Condition, the threads are signalled in FIFO order, apparently. So, the first thread to wait for insertion will be signalled first. However, these are implementation details! Do not rely on them.

an implementation is not required to define exactly the same guarantees or semantics for all three forms of waiting, nor is it required to support interruption of the actual suspension of the thread

like image 73
Chris Dennett Avatar answered Sep 22 '22 08:09

Chris Dennett