Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Circular Buffer Implementation in Java

11 min readbeginner
Website QA and SEO audits

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

A ring buffer stores a fixed number of elements in one contiguous block and moves two integer indices instead of moving data: writes advance one cursor, reads advance the other, and both wrap at the end of the block. Nothing is ever shifted and no node is ever allocated, which is why it beats a linked structure at the same big-O. The one real design constraint is that head == tail is ambiguous: it means both empty and full. The three honest fixes are a separate count field, deliberately wasting one slot, or letting the cursors run free and masking with capacity minus one when capacity is a power of two. On top sit two policy choices: overwrite the oldest or reject the write when full, and whether one producer and one consumer may run without a lock, which needs only that the writer publishes its cursor after the payload and the reader loads that cursor before the payload. The eight languages diverge because each answers different questions: does an array hold values or references, does an integer wrap or trap or grow without bound, what does the memory model demand to publish a cursor, and must a vacated slot be cleared so the collector can reclaim what it held.

Circular Buffer in Java: what you actually reach for

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.

Java implementation

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. They insist that a vacated slot be set to null, insist on offer and poll naming with a boolean or null result rather than a checked exception for the ordinary full and empty cases, and for the concurrent variant insist on VarHandle or volatile cursors instead of synchronizing the whole buffer.
java
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 Free

The Java-specific 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. 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.

Performance in Java, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Circular Buffer between languages.

Real-World Applications

Circular Buffer applies wherever its problem shape appears in your own code. In Java, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Circular Buffer helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Circular Buffer appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Circular Buffer over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Circular Buffer to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying for Devin, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.