Skip to content

Instantly share code, notes, and snippets.

@lambdaydoty
Created May 2, 2025 23:22
Show Gist options
  • Save lambdaydoty/0e364c51babf7c39c459dc234240c879 to your computer and use it in GitHub Desktop.
Save lambdaydoty/0e364c51babf7c39c459dc234240c879 to your computer and use it in GitHub Desktop.
Circular Buffer with Concurrency
public class CircularBuffer<T> {
private final T[] buffer;
private int head = 0;
private int tail = 0;
private int size = 0;
private final int capacity;
public CircularBuffer(int capacity) {
this.capacity = capacity;
buffer = (T[]) new Object[capacity];
}
public synchronized boolean isFull() {
return size == capacity;
}
public synchronized boolean isEmpty() {
return size == 0;
}
public synchronized void add(T item) {
while (isFull()) {
try {
wait(); // wait for space
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
buffer[tail] = item;
tail = (tail + 1) % capacity;
size++;
notifyAll(); // signal waiting readers
}
public synchronized T remove() {
while (isEmpty()) {
try {
wait(); // wait for data
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
T item = buffer[head];
buffer[head] = null;
head = (head + 1) % capacity;
size--;
notifyAll(); // signal waiting writers
return item;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment