Quick revision
The short answer
A ring buffer keeps its elements in a fixed Object[] with a head index and a count, and computes positions with (head + i) % capacity, or with a bit mask when the capacity is a power of two, so indexes wrap around to the start of the array. Because Java cannot create a generic array with new T[n], we store an Object[] and cast on read under @SuppressWarnings("unchecked"). Following the Queue contract, offer returns false when full and poll returns null when empty, poll clears the slot so the buffer does not keep dead objects alive, and the class is not thread safe.
What to remember
In this answer, we built a fixed-capacity RingBuffer<T> on an Object[] with a head index and a count, so empty and full are easy to tell apart. Positions wrap with (head + i) % capacity, or a mask when the capacity is a power of two. Because type erasure forbids new T[n], we store Object[] and cast each element on read under @SuppressWarnings("unchecked"). offer returns false when full and poll returns null when empty, poll clears its slot to avoid loitering references, and for concurrency we use ArrayBlockingQueue or a single-producer, single-consumer design with release and acquire ordering.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A ring buffer keeps its elements in a fixed Object[] with a head index and a count, and computes positions with (head + i) % capacity, or with a bit mask when the capacity is a power of two, so indexes wrap around to the start of the array. Because Java cannot create a generic array with new T[n], we store an Object[] and cast on read under @SuppressWarnings("unchecked"). Following the Queue contract, offer returns false when full and poll returns null when empty, poll clears the slot so the buffer does not keep dead objects alive, and the class is not thread safe.
Why this question is asked
Ring buffers are everywhere once we look: logging buffers, metrics windows, network packet queues, and the core of high-performance libraries such as the LMAX Disruptor. Interviewers like this question because it is small enough to write fully, yet it tests index arithmetic, Java generics and the Queue contract, and it opens a conversation about concurrency. In this answer, we will recap how a ring buffer works, handle wrap-around, deal with the generic array problem, write the class, test its behaviour, and look at thread safety.
1A Quick Recap of How a Ring Buffer Works
A ring buffer, also called a circular buffer, is a queue with a fixed capacity backed by an array. Instead of shifting elements when we remove from the front, which costs O(n) in an ArrayList, it keeps an index to the front element, called head, and moves that index forward. New elements are written after the last element. When an index reaches the end of the array, it wraps around to position 0, so the array behaves as if its ends were joined in a ring.
We need to know where the front is and how many elements there are. Keeping head and a count is the simplest choice, because it makes "empty" (count == 0) and "full" (count == capacity) easy to tell apart. Keeping head and tail indexes alone is ambiguous, because head == tail can mean either empty or full, which is why such designs keep one slot unused or a separate count.
| Slot | Content | Note |
|---|---|---|
| 0 | E | written after wrap-around: (2 + 2) % 4 = 0 |
| 1 | F | (2 + 3) % 4 = 1 |
| 2 | C | head = 2, the next element poll() returns |
| 3 | D | count = 4, so the buffer is full |
2Handling Wrap-Around
The position of the i-th element is (head + i) % capacity. So the next free slot for offer is (head + count) % capacity, and after poll the new head is (head + 1) % capacity. The remainder operator brings any index past the end back to the start.
When the capacity is a power of two, such as 1024, we can replace % capacity with & (capacity - 1), a bit mask that keeps the low bits. It gives the same result for non-negative numbers and avoids a division, which matters in very hot code. For a general-purpose class, % is clear and fast enough; we just must remember that head + count can never overflow here, because both are below the capacity.
3The Generic Array Problem
Inside a generic class RingBuffer<T>, writing new T[capacity] does not compile. The reason is type erasure: at runtime the JVM does not know what T is, because generic types are removed after compilation, but every array must know its exact element type when it is created, so that it can check every store. So Java cannot create an array of an unknown type.
The standard solution, used by ArrayList and ArrayDeque themselves, is to store an Object[] and cast each element to T when we read it. The cast is unchecked, meaning the compiler cannot verify it, so it warns. Since only offer(T) ever writes into the array, every element really is a T and the cast is safe; we mark it with @SuppressWarnings("unchecked") on the smallest possible scope. Casting the whole array, (T[]) new Object[n], also compiles, but it fails with ClassCastException if that array ever escapes to code that expects a real T[], so the per-element cast is safer.
4Writing RingBuffer<T>
Here is the complete class. It mirrors the Queue methods: offer returns false when there is no room, and poll returns null when there is nothing to return.
Notice the line items[head] = null. Without it, the array keeps a reference to every polled object until that slot is overwritten, which could be a long time in a quiet buffer. Objects that are logically removed but still reachable are called loitering references, and they are a classic memory leak in hand-written collections. Notice also that we reject null: since poll uses null to mean empty, storing null would make an element indistinguishable from an empty buffer, which is the same reason ArrayDeque and ArrayBlockingQueue reject it.
5Checking the Behaviour
A short test walks through filling, wrapping and emptying.
Some ring buffers overwrite the oldest element when full instead of refusing, which suits a "last N log lines" buffer. That is a design choice to state; the Queue-style contract above refuses.
6Thread Safety
This class is not thread safe. If two threads call offer at the same time, both can read the same count, write to the same slot and lose an element, and without synchronisation a consumer thread may not even see the producer's writes. For general concurrent use, the JDK already has ArrayBlockingQueue, a bounded ring buffer protected by a lock, with blocking put and take as well as offer and poll. For the special case of exactly one producer thread and one consumer thread, a lock-free design is possible, as the follow-up below explains.
7Follow-up questions
How would you make it safe for one producer and one consumer without locks?
Give each side its own counter: the consumer alone writes head, the producer alone writes tail, both as ever-increasing long values, and make the capacity a power of two so the slot is counter & mask. The producer checks tail - head < capacity, writes the element into the slot, then publishes the new tail with a release write (a volatile write, or VarHandle.setRelease, or AtomicLong.lazySet). The consumer reads tail with an acquire read, and if head < tail it reads the slot, clears it, and publishes head + 1 the same way. Because each counter has exactly one writer, there are no races to resolve, and the release and acquire ordering guarantees the consumer sees the element before it sees the new tail. Libraries such as JCTools and the Disruptor add padding against false sharing.
Why not use (T[]) new Object[n] inside the class?
It works while the array stays private, because erasure turns T[] into Object[] at runtime. The danger is a method like toArray() that returns it: the caller expects, say, String[], and the JVM throws ClassCastException at the call site. Casting element by element keeps the unchecked cast where we can prove it is safe.
What is the time complexity of each operation?
offer, poll and size are all O(1): a few index calculations and one array write or read, with no shifting and no allocation. Memory is fixed at the capacity, which is often the main reason to choose a ring buffer.
8Conclusion
In this answer, we built a fixed-capacity RingBuffer<T> on an Object[] with a head index and a count, so empty and full are easy to tell apart. Positions wrap with (head + i) % capacity, or a mask when the capacity is a power of two. Because type erasure forbids new T[n], we store Object[] and cast each element on read under @SuppressWarnings("unchecked"). offer returns false when full and poll returns null when empty, poll clears its slot to avoid loitering references, and for concurrency we use ArrayBlockingQueue or a single-producer, single-consumer design with release and acquire ordering.
Open with
I would back it with an Object array plus two ints, head for the oldest element and count for how many are stored, because with count, empty and full are unambiguous. offer checks whether count equals the capacity and returns false if so, otherwise it writes at head plus count modulo capacity and increments count. poll returns null if count is zero; otherwise it reads the slot at head, sets that slot to null so the buffer does not keep the object alive, advances head modulo capacity and decrements count.
Then, if they want more
If the capacity is a power of two I can use a bit mask instead of the modulo. On generics, new T of n does not compile because of type erasure: the runtime does not know T, but arrays need their element type when created.
So I store Object and cast on read, with SuppressWarnings unchecked on just that line; it is safe because only offer, which takes a T, writes into the array. I would reject null in offer, since poll uses null for empty, which mirrors the Queue contract. All operations are O(1).
It is not thread safe; for shared use I would reach for ArrayBlockingQueue, or for exactly one producer and one consumer, separate head and tail counters published with release and acquire semantics.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Implement a generic fixed-capacity ring buffer class RingBuffer<T> with offer(T), poll()...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/1c13298532/