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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.