Site Search:

SleepyBoundedBuffer.java

 SleepyBoundedBuffer.java

/**
* SleepyBoundedBuffer
* <p/>
* Bounded buffer using crude blocking
*/
public class SleepyBoundedBuffer <V> extends BaseBoundedBuffer<V> {
int SLEEP_GRANULARITY = 60;

public SleepyBoundedBuffer() {
this(100);
}

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

public void put(V v) throws InterruptedException {
while (true) {
synchronized (this) {
if (!isFull()) {
doPut(v);
return;
}
}
Thread.sleep(SLEEP_GRANULARITY);
System.out.print("p");
}
}

public V take() throws InterruptedException {
while (true) {
synchronized (this) {
if (!isEmpty())
return doTake();
}
Thread.sleep(SLEEP_GRANULARITY);
System.out.print("t");
}
}
}

class SleepyBoundedBufferExampleUsage {
private SleepyBoundedBuffer<String> buffer;
int SLEEP_GRANULARITY = 50;

public SleepyBoundedBufferExampleUsage() {
this.buffer = new SleepyBoundedBuffer<>();
}

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

}

void useBuffer() throws InterruptedException {
String item = buffer.take();
// use item
System.out.println("took item " + item);
}
}

The SleepyBoundedBuffer class extends BaseBoundedBuffer and implements a crude form of blocking by repeatedly checking buffer state and sleeping briefly when full (on put) or empty (on take). Unlike the balking strategy of GrumpyBoundedBuffer, this approach uses a busy-wait loop with Thread.sleep() to wait for conditions to change, which is simple but inefficient and CPU-wasteful under high contention. The example usage shows a consumer thread polling for a message while a producer adds it after a delay. This illustrates a basic, manually-controlled blocking mechanism often used in early or educational concurrent programming models.

No comments:

Post a Comment