00:00

Problem Statement

Input/Output Examples

Visual Explanation

Blocking puts the waiting thread to sleep instead of letting it spin. The poison value avoids having to interrupt the consumer.

Approaches

Both approaches use the same producer and consumer. One relies on ArrayBlockingQueue; the other implements the buffer by hand.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. The consumer records what it takes, and the results are printed only after both threads have finished, so the output is identical on every run (checked over 25 runs).

Complexity Analysis

Here n is the number of items. Each item is put and taken once; the buffer never holds more than its capacity.

Interview Tips and Recommended Approach

  • Prefer BlockingQueue in real code; it is correct and well tested.
  • Wait in a loop in hand-written buffers.
  • Plan shutdown. A poison value, or interrupting the consumer, ends it cleanly.
  • Scale out. With several consumers, send one poison value per consumer.

Recommended Approach: ArrayBlockingQueue

Why: it delegates all synchronisation to a tested JDK class, leaving only the producer and consumer logic in your code.