While reading the source code of ArrayBlockingQueue
, I found a comment explaining that it uses "the classic two-condition algorithm found in any textbook":
/*
* Concurrency control uses the classic two-condition algorithm
* found in any textbook.
*/
/** Main lock guarding all access */
private final ReentrantLock lock;
/** Condition for waiting takes */
private final Condition notEmpty;
/** Condition for waiting puts */
private final Condition notFull;
Why does it use the classic two-condition (notEmpty, notFull) algorithm?
You already had a good comment. Only as a complement.
ArrayBlockingQueue is a State-Dependent class. This means that this class has operations that only can be performed with some preconditions.
The writer threads will only wait if the precondition (notFull) is false.
// If the queue is full then writer needs to wait.
// Atomically releases the lock and waits for the signal (notFull.signal() fired by a reader).
while (count == items.length)
notFull.await();
For readers the concept is identical, but using the notEmpty condition.
// If the queue is empty then reader needs to wait.
// Atomically releases the lock and waits for the signal (notEmpty.signal() fired by a writter).
while (count == 0)
notEmpty.await();
When a thread wakes up then you need 2 main things:
1 - Get the lock
2 - Re-Test the condition
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With