Site Search:

BaseBoundedBuffer.java

 BaseBoundedBuffer.java

/**
* BaseBoundedBuffer
* <p/>
* Base class for bounded buffer implementations
*
*/
public abstract class BaseBoundedBuffer <V> {
private final V[] buf;
private int tail;
private int head;
private int count;

protected BaseBoundedBuffer(int capacity) {
this.buf = (V[]) new Object[capacity];
}

protected synchronized final void doPut(V v) {
buf[tail] = v;
if (++tail == buf.length)
tail = 0;
++count;
}

protected synchronized final V doTake() {
V v = buf[head];
buf[head] = null;
if (++head == buf.length)
head = 0;
--count;
return v;
}

public synchronized final boolean isFull() {
return count == buf.length;
}

public synchronized final boolean isEmpty() {
return count == 0;
}
}

The BaseBoundedBuffer<V> class is an abstract foundation for building various bounded buffer implementations. It manages a circular array buffer with synchronized internal operations (doPut, doTake) to insert and remove elements, along with utility methods to check if the buffer is full or empty. This base class encapsulates the low-level indexing and storage logic, allowing subclasses to focus on synchronization and coordination policies. In the following examples, we will develop multiple concrete implementations that extend BaseBoundedBuffer, each using a different concurrency strategy—such as intrinsic locks, explicit locks, or advanced synchronizers—to demonstrate various approaches to building thread-safe producer-consumer buffers.

No comments:

Post a Comment