Created
May 2, 2025 23:22
-
-
Save lambdaydoty/0e364c51babf7c39c459dc234240c879 to your computer and use it in GitHub Desktop.
Circular Buffer with Concurrency
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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