In the previous chapter, we saw that threads need to cooperate with one another to achieve significant functionality. Cooperation entails communication; ReentrantLock allows a thread to signal to other threads. We use this mechanism to implement a Concurrent FIFO queue:
public class ConcurrentQueue { final Lock lck = new ReentrantLock(); final Condition needSpace = lck.newCondition(); final Condition needElem = lck.newCondition(); final int[] items; int tail, head, count; public ConcurrentQueue(int cap) { this.items = new int[cap]; }
The class holds a reentrant lock in its lck field. It also has two conditions, namely needSpace and needElem. We will see how these are used. The queue elements are stored in an ...