Last active
July 6, 2025 14:52
-
-
Save krisraich/0057592bc144f24452d5b6ed8ef8001b to your computer and use it in GitHub Desktop.
Fast threadsafe insert only random access circular buffer
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
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