Implement a thread-safe circular buffer with non-blocking write and read

Quick Overview

Implement a fixed-capacity circular buffer that producers write to and consumers read from in FIFO order, where writes fail when the buffer is full and reads return -1 when it is empty. It tests wrap-around index arithmetic, telling a full buffer from an empty one, and mutex-based thread safety.

Implement a thread-safe circular buffer with non-blocking write and read

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design and implement a thread-safe circular buffer (also known as a ring buffer) that supports producer-consumer operations. The buffer has a fixed `capacity` and uses wrap-around logic when the end of the internal array is reached. A producer writes data into the buffer, and a consumer reads data from the buffer in FIFO order. If the buffer is full, the write operation should fail and return `False`. If the buffer is empty, the read operation should return `-1`. The buffer must be safe for concurrent access using mutex-based synchronization. All operations should run in constant time. Implement the following methods: - `write(value: int) -> bool`: write a value into the ring buffer. Return `True` if the write was successful, or `False` if the buffer is full. - `read() -> int`: read and remove the oldest value from the ring buffer. Return `-1` if the buffer is empty. - `size() -> int`: return the current number of elements in the buffer. - `isEmpty() -> bool`: return `True` if the buffer contains no elements, `False` otherwise. - `isFull() -> bool`: return `True` if the buffer is at full capacity, `False` otherwise. Example 1: ```text Input: ["RingBuffer", "write", "write", "write", "read", "read", "write", "read", "read", "isEmpty"] [[3], [10], [20], [30], [], [], [40], [], [], []] Output: [null, true, true, true, 10, 20, true, 30, 40, true] Explanation: buf = RingBuffer(3) capacity = 3, buffer: [] buf.write(10) -> True buffer: [10] buf.write(20) -> True buffer: [10, 20] buf.write(30) -> True buffer: [10, 20, 30] (full) buf.read() -> 10 buffer: [20, 30] buf.read() -> 20 buffer: [30] buf.write(40) -> True buffer: [30, 40] (wraps around) buf.read() -> 30 buffer: [40] buf.read() -> 40 buffer: [] buf.isEmpty() -> True buffer is now empty ``` Example 2: ```text Input: ["RingBuffer", "read", "write", "isFull", "write", "isFull", "read", "read", "size"] [[1], [], [5], [], [7], [], [], [], []] Output: [null, -1, true, true, false, true, 5, -1, 0] Explanation: buf = RingBuffer(1) capacity = 1, buffer: [] buf.read() -> -1 buffer is empty buf.write(5) -> True buffer: [5] buf.isFull() -> True capacity is 1, buffer is full buf.write(7) -> False buffer is full, write rejected buf.isFull() -> True still full buf.read() -> 5 buffer: [] buf.read() -> -1 buffer is empty again buf.size() -> 0 buffer is empty ``` ```hint Full or empty? With only a read index and a write index, the two point at the same slot both when the buffer is empty and when it is full. Decide what extra state lets every method tell those cases apart in constant time. ``` ```hint Scope of the lock Every method touches shared fields, including the ones that only report state. Also think about what a caller can safely conclude from an `isFull()` result once the lock has been released. ``` ### Constraints & Assumptions - `1 <= capacity <= 10^4` - `-10^9 <= value <= 10^9` - At most 10^5 calls in total across all methods. ### Clarifying Questions to Ask - Values can be negative, so -1 is also a value a producer can store. Is the -1 return for an empty buffer acceptable, or should `read` report emptiness some other way? - How many producer and consumer threads will use the buffer at once? Exactly one of each would allow a design without a mutex. ### What a Strong Answer Covers - A fixed array with read and write indices that wrap using modular arithmetic, and an unambiguous rule for telling a full buffer from an empty one. - FIFO order preserved across the wrap-around, with constant time for every operation. - A mutex guarding every access to shared state, including `size`, `isEmpty` and `isFull`. - The limits of the contract: the -1 sentinel colliding with a stored -1, and the race when a caller checks `isFull()` and then calls `write()`. ### Follow-up Questions - How would you change `write` and `read` so they wait for space or data instead of failing immediately? - With exactly one producer and one consumer, how would you remove the mutex, and what memory-ordering guarantees would you need? - How would you add an overwrite mode that drops the oldest value when a write arrives at a full buffer? - How would you avoid the modulo operation on every call?

Overview: Implement a fixed-capacity circular buffer that producers write to and consumers read from in FIFO order, where writes fail when the buffer is full and reads return -1 when it is empty. It tests wrap-around index arithmetic, telling a full buffer from an empty one, and mutex-based thread safety.

Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design and implement a thread-safe circular buffer (also known as a ring buffer) that supports producer-consumer operations. The buffer has a fixed capacity and uses wrap-around logic when the end of the internal array is reached.

A producer writes data into the buffer, and a consumer reads data from the buffer in FIFO order. If the buffer is full, the write operation should fail and return False. If the buffer is empty, the read operation should return -1.

The buffer must be safe for concurrent access using mutex-based synchronization. All operations should run in constant time.

Implement the following methods:

  • write(value: int) -> bool : write a value into the ring buffer. Return True if the write was successful, or False if the buffer is full.
  • read() -> int : read and remove the oldest value from the ring buffer. Return -1 if the buffer is empty.
  • size() -> int : return the current number of elements in the buffer.
  • isEmpty() -> bool : return True if the buffer contains no elements, False otherwise.
  • isFull() -> bool : return True if the buffer is at full capacity, False otherwise.

Example 1:

Input:
["RingBuffer", "write", "write", "write", "read", "read", "write", "read", "read", "isEmpty"]
[[3],          [10],    [20],    [30],    [],     [],     [40],    [],     [],     []]

Output: [null, true, true, true, 10, 20, true, 30, 40, true]

Explanation:
buf = RingBuffer(3)     capacity = 3, buffer: []
buf.write(10)           -> True    buffer: [10]
buf.write(20)           -> True    buffer: [10, 20]
buf.write(30)           -> True    buffer: [10, 20, 30] (full)
buf.read()              -> 10      buffer: [20, 30]
buf.read()              -> 20      buffer: [30]
buf.write(40)           -> True    buffer: [30, 40] (wraps around)
buf.read()              -> 30      buffer: [40]
buf.read()              -> 40      buffer: []
buf.isEmpty()           -> True    buffer is now empty

Example 2:

Input:
["RingBuffer", "read", "write", "isFull", "write", "isFull", "read", "read", "size"]
[[1],          [],     [5],     [],       [7],     [],       [],     [],     []]

Output: [null, -1, true, true, false, true, 5, -1, 0]

Explanation:
buf = RingBuffer(1)     capacity = 1, buffer: []
buf.read()              -> -1      buffer is empty
buf.write(5)            -> True    buffer: [5]
buf.isFull()            -> True    capacity is 1, buffer is full
buf.write(7)            -> False   buffer is full, write rejected
buf.isFull()            -> True    still full
buf.read()              -> 5       buffer: []
buf.read()              -> -1      buffer is empty again
buf.size()              -> 0       buffer is empty

Constraints & Assumptions

  • 1 <= capacity <= 10^4
  • -10^9 <= value <= 10^9
  • At most 10^5 calls in total across all methods.

Clarifying Questions to Ask Guidance

  • Values can be negative, so -1 is also a value a producer can store. Is the -1 return for an empty buffer acceptable, or should read report emptiness some other way?
  • How many producer and consumer threads will use the buffer at once? Exactly one of each would allow a design without a mutex.

What a Strong Answer Covers Guidance

  • A fixed array with read and write indices that wrap using modular arithmetic, and an unambiguous rule for telling a full buffer from an empty one.
  • FIFO order preserved across the wrap-around, with constant time for every operation.
  • A mutex guarding every access to shared state, including size , isEmpty and isFull .
  • The limits of the contract: the -1 sentinel colliding with a stored -1, and the race when a caller checks isFull() and then calls write() .

Follow-up Questions Guidance

  • How would you change write and read so they wait for space or data instead of failing immediately?
  • With exactly one producer and one consumer, how would you remove the mutex, and what memory-ordering guarantees would you need?
  • How would you add an overwrite mode that drops the oldest value when a write arrives at a full buffer?
  • How would you avoid the modulo operation on every call?