The producer/consumer pattern

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 needElemWe will see how these are used. The queue elements are stored in an ...

Get Concurrent Patterns and Best Practices now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.