Skip to content

Instantly share code, notes, and snippets.

@krisraich
Last active July 6, 2025 14:52
Show Gist options
  • Save krisraich/0057592bc144f24452d5b6ed8ef8001b to your computer and use it in GitHub Desktop.
Save krisraich/0057592bc144f24452d5b6ed8ef8001b to your computer and use it in GitHub Desktop.
Fast threadsafe insert only random access circular buffer
import java.util.RandomAccess;
/**
* Fast threadsafe insert only random access circular buffer
*/
public class CircularBuffer<T> implements RandomAccess {
private final Object[] items;
private int head = 0;
private boolean isPopulated = false;
public CircularBuffer(int size) {
if (size <= 0) {
throw new IllegalArgumentException();
}
this.items = new Object[size];
}
public synchronized void add(T value) {
items[head++] = value;
if (head == items.length) {
head = 0;
isPopulated = true;
}
}
public T get(int index) {
if (index < 0 || index >= size()) {
throw new ArrayIndexOutOfBoundsException(index);
}
//noinspection unchecked
return (T) items[index];
}
public int size() {
return isPopulated ? items.length : head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment