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?
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.
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.