📦 What Is a Bounded Buffer?
A bounded buffer is a fixed-size queue that:
- Allows producers to
put()
items. - Allows consumers to
take()
items. - Blocks producers if the buffer is full.
- Blocks consumers if the buffer is empty.
✅ Key Features:
- Thread-safe with
synchronized
- Uses
wait()
/notifyAll()
for coordination - Fixed-size circular buffer
🧱 Code: Simple Bounded Buffer
public class BoundedBuffer<T> {
private final Object[] buffer;
private int head = 0, tail = 0, count = 0;
private final int capacity;
public BoundedBuffer(int capacity) {
this.capacity = capacity;
this.buffer = new Object[capacity];
}
public synchronized void put(T item) throws InterruptedException {
while (count == capacity) {
wait(); // Buffer full, wait for space
}
buffer[tail] = item;
tail = (tail + 1) % capacity;
count++;
notifyAll(); // Wake up waiting consumers
}
@SuppressWarnings("unchecked")
public synchronized T take() throws InterruptedException {
while (count == 0) {
wait(); // Buffer empty, wait for item
}
T item = (T) buffer[head];
head = (head + 1) % capacity;
count--;
notifyAll(); // Wake up waiting producers
return item;
}
public synchronized int size() {
return count;
}
}
🧪 Example Usage
public class Main {
public static void main(String[] args) {
BoundedBuffer<Integer> buffer = new BoundedBuffer<>(5);
// Producer
Thread producer = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
try {
buffer.put(i);
System.out.println("Produced: " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Consumer
Thread consumer = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
try {
int val = buffer.take();
System.out.println("Consumed: " + val);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
}
}
✅ Summary
Feature | Included? |
---|---|
Thread-safe | ✅ Yes (with synchronized ) |
Bounded | ✅ Yes (fixed-size buffer) |
Blocking put() | ✅ Waits if full |
Blocking take() | ✅ Waits if empty |
Coordination | ✅ wait() /notifyAll() |