Circular Buffer Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Circular Buffer runs in O(1) time and O(n) space, in Java as in every other language.
- ✓java.util.ArrayDeque is the contiguous ring in the JDK: one Object array with head and tail indices, wrapping by inc and dec helpers comparing against the array length, not by masking, so capacity is arbitrary, not a power of two: the constructor allocates numElements + 1 and growth adds oldCapacity < 64 ?
- ✓Reviewers accept an Object[] field with a cast at the read boundary and reject (E[]) new Object[n] stored in an E[] field, because that array really is an Object[] and any code that hands it out as E[] earns a ClassCastException where erasure meets the concrete type, or quiet heap pollution.
- ✓The Java trap: Two bites are Java's alone. First, % on a negative int returns a negative int, so a free-running int cursor that has wrapped past Integer.MAX_VALUE yields a negative index and an ArrayIndexOutOfBoundsException, while & (capacity - 1) keeps working because the two's complement low bits are still the right ones.
- ✓An Object[] holds references, so every element is a pointer chase into the heap and every store fires a card-marking write barrier.
What Circular Buffer actually is
Circular Buffer in Java: what you actually reach for
Java implementation
public final class RingBuffer<E> {
// Object[], not E[]: generic arrays do not survive erasure, and a field
// typed E[] backed by an Object[] throws ClassCastException the moment
// that array is handed to a caller as E[].
private final Object[] buf;
private final int mask;
private int head; // index of the oldest element
private int count; // count field: full and empty are distinguishable
public RingBuffer(int capacity) {
if (Integer.bitCount(capacity) != 1) {
throw new IllegalArgumentException("capacity must be a power of two");
}
this.buf = new Object[capacity];
this.mask = capacity - 1;
}
public int size() { return count; }
/** Overwrite-oldest. Returns the evicted element, or null if none. */
public E offerOverwrite(E e) {
int tail = (head + count) & mask;
E evicted = null;
if (count == buf.length) {
@SuppressWarnings("unchecked") E old = (E) buf[tail]; // tail == head
evicted = old;
head = (head + 1) & mask;
} else {
count++;
}
buf[tail] = e;
return evicted;
}
@SuppressWarnings("unchecked")
public E poll() {
if (count == 0) return null;
E e = (E) buf[head];
buf[head] = null; // ArrayDeque does this too: a stale slot pins the graph
head = (head + 1) & mask;
count--;
return e;
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Circular Buffer?
java.util.ArrayDeque is the contiguous ring in the JDK: one Object array with head and tail indices, wrapping by inc and dec helpers comparing against the array length, not by masking, so capacity is arbitrary, not a power of two: the constructor allocates numElements + 1 and growth adds oldCapacity < 64 ? oldCapacity + 2 : oldCapacity >> 1. It grows instead of rejecting and never overwrites. java.util.concurrent.ArrayBlockingQueue is the fixed-capacity one, a single array behind a single ReentrantLock, where put blocks and offer returns false. Neither drops the oldest, so that policy is yours to write. For raw bytes, java.nio.ByteBuffer already carries position and limit. When you need the genuinely lock-free single-producer-single-consumer version, the ecosystem standards are JCTools, whose org.jctools.queues.SpscArrayQueue is exactly this structure, and the LMAX Disruptor RingBuffer.
What is the most common Java mistake when implementing Circular Buffer?
Two bites are Java's alone. First, % on a negative int returns a negative int, so a free-running int cursor that has wrapped past Integer.MAX_VALUE yields a negative index and an ArrayIndexOutOfBoundsException, while & (capacity - 1) keeps working because the two's complement low bits are still the right ones. That is why the free-running-counter rings, JCTools and the Disruptor, require a power-of-two capacity. Second, without volatile, a VarHandle or some other happens-before edge, the Java Memory Model permits the producer's plain write to the cursor never to become visible to the consumer at all. The failure mode is not a crash or a torn read; it is a queue that looks permanently empty.
How does Circular Buffer actually perform in Java?
An Object[] holds references, so every element is a pointer chase into the heap and every store fires a card-marking write barrier. Only int[], long[] and double[] give real contiguity, and a ring of Integer allocates on every push outside the cached -128 to 127 range. Stale references in vacated slots keep whole object graphs reachable, which is why ArrayDeque nulls them out. In a concurrent ring, head and tail declared as adjacent fields share a cache line and ping-pong between cores; pad them, or use jdk.internal.vm.annotation.Contended. Escape analysis will never flatten the backing array. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.