O'Reilly logo

Concurrent Patterns and Best Practices by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required