Site Search:

GrumpyBoundedBuffer.java

 GrumpyBooundedBuffer.java

/**
* GrumpyBoundedBuffer
* <p/>
* Bounded buffer that balks when preconditions are not met
*/
public class GrumpyBoundedBuffer <V> extends BaseBoundedBuffer<V> {
public GrumpyBoundedBuffer() {
this(100);
}

public GrumpyBoundedBuffer(int size) {
super(size);
}

public synchronized void put(V v) throws BufferFullException {
if (isFull())
throw new BufferFullException();
doPut(v);
}

public synchronized V take() throws BufferEmptyException {
if (isEmpty())
throw new BufferEmptyException();
return doTake();
}
}

class ExampleUsage {
private GrumpyBoundedBuffer<String> buffer;
int SLEEP_GRANULARITY = 50;

public ExampleUsage() {
this.buffer = new GrumpyBoundedBuffer<>();
}

public static void main(String...args) {
ExampleUsage eu = new ExampleUsage();
new Thread(()->{
try {
eu.useBuffer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
try {
Thread.sleep(5000);
eu.buffer.put("A-Message");
} catch (InterruptedException e) {
e.printStackTrace();
}

}

void useBuffer() throws InterruptedException {
while (true) {
try {
String item = buffer.take();
// use item
System.out.println("took item " + item);
break;
} catch (BufferEmptyException e) {
Thread.sleep(SLEEP_GRANULARITY);
System.out.print(".");
}
}
}
}

class BufferFullException extends RuntimeException {
}

class BufferEmptyException extends RuntimeException {
}

The GrumpyBoundedBuffer is a simple extension of BaseBoundedBuffer that immediately throws an exception (BufferFullException or BufferEmptyException) if an operation is attempted when the buffer is not in the appropriate state, rather than blocking or waiting. This "balking" behavior is useful in scenarios where the calling thread should decide how to respond to unavailability. The accompanying ExampleUsage class demonstrates this pattern by polling the buffer in a loop, sleeping briefly between retries, until a message becomes available. This approach illustrates a non-blocking, retry-based consumer pattern commonly used when responsiveness or control over timing is important.

No comments:

Post a Comment