Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why Concurrency control uses the classic two-condition algorithm

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?

like image 856
fuyou001 Avatar asked Apr 13 '13 13:04

fuyou001


1 Answers

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

like image 107
Pedro Gandola Avatar answered Oct 17 '22 06:10

Pedro Gandola