AlgoMaster Logo
AlgoMasterDesign a Closable Bounded Queuemedium

Design a Closable Bounded Queue

medium

Design a thread-safe bounded queue that supports clean producer-consumer shutdown.

Implement the ClosableBoundedQueue class. The queue stores integers and has a fixed capacity.

  • put(item) adds item to the back of the queue. It waits while the queue is full.
  • take() removes and returns the item at the front. It waits while the queue is empty.
  • close() permanently closes the queue and wakes every blocked operation.

Closing the queue follows these rules:

  • Items accepted before close() remain available and must be returned in FIFO order.
  • Once the closed queue becomes empty, take() returns the language-specific no-item result instead of waiting.
  • A put() that is waiting when the queue closes must wake and fail without adding its item.
  • Every put() started after closure must fail immediately.
  • Calling close() more than once has no additional effect.

The language-specific results are:

  • Java: take() returns null; rejected put() throws IllegalStateException.
  • Python: take() returns None; rejected put() raises RuntimeError.
  • C++: take() returns nullopt; rejected put() throws runtime_error.
  • Go: Take() returns (0, false); rejected Put() returns false.
  • C#: Take() returns null; rejected Put() throws InvalidOperationException.

Java and C# must preserve normal interruption behavior. An interrupted operation must exit without adding or removing an item.

The judge creates producer and consumer threads around one or more queue instances. Do not create worker threads inside the queue. Waiting must not use busy-waiting.

Standard concurrency and collection APIs are preloaded, so you do not need import, include, package, or using statements.

Example 1:

Input:

Output:

Explanation: Closing does not discard queued items. After both items are drained, take() reports that no more items can arrive.

Example 2:

Input:

Output:

Explanation: Closure rejects the blocked producer but preserves the item that was accepted earlier.

Constraints

  • 1 <= capacity <= 1000
  • -1_000_000 <= item <= 1_000_000
  • At most 10000 method calls are made on one queue.
  • Any number of threads may call put, take, and close concurrently.
  • Once closed, a queue never reopens.
  • No fairness order is required among blocked threads.
Loading...

Input

capacity = 2
put(10)
put(20)
close()
take()
take()
take()

Output

10
20
no item

Run is a quick check against the first couple of scenarios, which is roughly what these examples describe. Submit puts your class under the full set, which stays hidden.