A bounded buffer
A bounded buffer is one with a finite capacity. You can only buffer a certain amount of elements in it. When there is no more space left to store the elements, the producer threads putting the elements wait for someone to consume some of the elements.
On the other hand, the consumer threads cannot take elements from an empty buffer. In such cases, the consumer thread will need to wait for someone to insert elements into the buffer.
Here comes the code, which we will explain as we go:
public abstract class Buffer { private final Integer[] buf; private int tail; private int head; private int cnt;
The elements are stored in an array of integers, buf
:
As shown in the preceding diagram, the field tail
 points to the next empty position to put the element in. In the provided diagram, three elements were inserted and none were taken. The first element to be consumed is 2, which resides at the index 0 of the internal array. This is the index we hold in the head
field. The value of count...