Loading...
Loading...
In concurrent programming, the Producer-Consumer pattern is a classic synchronization problem where one or more producer threads generate data and place it into a shared buffer, while one or more consumer threads retrieve and process that data.
Your task is to implement a bounded, thread-safe queue in Java that supports concurrent producers and consumers. The queue must handle blocking behavior when it is full (producers wait) or empty (consumers wait).
Implement a class BoundedQueue<T> with the following API:
class BoundedQueue<T> {
public BoundedQueue(int capacity) { ... }
public void put(T item) throws InterruptedException { ... } // blocks if full
public T take() throws InterruptedException { ... } // blocks if empty
public int size() { ... } // current number of elements
public boolean isEmpty() { ... } // true if no elements
public boolean isFull() { ... } // true if at max capacity
}
put(item): Adds an item to the queue. If the queue is full, the calling thread blocks until space becomes available.take(): Removes and returns the front item. If the queue is empty, the calling thread blocks until an item is available.1 <= capacity <= 1000 1 <= number of commands <= 500 Values in PUT commands are integers: -10^9 <= x <= 10^9 No TAKE command will be issued when the queue would permanently block (guaranteed feasibility in single-threaded test simulation) Commands are executed sequentially in single-threaded tests; thread-safety is validated separately
For testing purposes, simulate the queue operations as a sequence of commands:
PUT x — enqueue value xTAKE — dequeue and record the front valueSIZE — record the current sizeIS_EMPTY — record true or falseIS_FULL — record true or falseInput: A capacity integer on the first line, followed by a list of commands.
Output: Results for TAKE, SIZE, IS_EMPTY, and IS_FULL commands, one per line.
Input:
capacity=3
PUT 10
PUT 20
PUT 30
SIZE
TAKE
TAKE
IS_EMPTY
Output:
3
10
20
false
Explanation: Three items are enqueued. SIZE returns 3. TAKE returns items in FIFO order (10, then 20). After two takes, one item remains, so IS_EMPTY is false.
ReentrantLock with two Condition objects: notFull (signal when an item is removed) and notEmpty (signal when an item is added). This is the idiomatic Java approach.synchronized methods with wait() / notifyAll(), though this is less fine-grained.LinkedList or circular array (ArrayDeque) works well.await()) instead of spinning in a loop.