Topic 30 of 30 · Expert
Build a bounded producer-consumer channel with explicit completion
Transfer positive integers through a capacity-two queue, sum them in a consumer and terminate with an explicit reserved sentinel.
Java 17+; compile each complete program as Main.java.
Problem statement
Transfer positive integers through a capacity-two queue, sum them in a consumer and terminate with an explicit reserved sentinel.
Demonstrate backpressure without unbounded accumulation.
Input: Positive integer work items; -1 reserved as completion.
Output: Sum of consumed values.
- One producer and one consumer.
- Work items positive.
- Both tasks must terminate or be interrupted on failure.
Sample 1
Input: 1,2,3,4 Output: 10
All accepted items consumed before sentinel.
Sample 2
Input: no work items then sentinel Output: 0
Consumer terminates without waiting forever.
Brute-force solution
An unbounded queue permits memory to grow indefinitely during producer bursts.
O(n) transfer work; wall time includes blocking.
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
BlockingQueue<Integer> queue=new ArrayBlockingQueue<>(2);
ExecutorService pool=Executors.newFixedThreadPool(2);
try{
Future<?> producer=pool.submit(()->{try{for(int i=1;i<=4;i++)queue.put(i);queue.put(-1);}catch(InterruptedException e){Thread.currentThread().interrupt();throw new RuntimeException(e);}});
Future<Integer> consumer=pool.submit(()->{int sum=0;while(true){int x=queue.take();if(x==-1)return sum;sum+=x;}});
int total=consumer.get(5,TimeUnit.SECONDS);producer.get(5,TimeUnit.SECONDS);System.out.println(total);if(total!=10)throw new AssertionError();
}finally{pool.shutdownNow();}
}
}
Optimized solution
ArrayBlockingQueue blocks admission at capacity and preserves FIFO completion order.
- Start producer and consumer together.
- Use put/take for blocking coordination.
- Send sentinel after accepted work.
- Bound waiting and cancel the pool on exit.
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
BlockingQueue<Integer> queue=new ArrayBlockingQueue<>(2);
ExecutorService pool=Executors.newFixedThreadPool(2);
try{
Future<?> producer=pool.submit(()->{try{for(int i=1;i<=4;i++)queue.put(i);queue.put(-1);}catch(InterruptedException e){Thread.currentThread().interrupt();throw new RuntimeException(e);}});
Future<Integer> consumer=pool.submit(()->{int sum=0;while(true){int x=queue.take();if(x==-1)return sum;sum+=x;}});
int total=consumer.get(5,TimeUnit.SECONDS);producer.get(5,TimeUnit.SECONDS);System.out.println(total);if(total!=10)throw new AssertionError();
}finally{pool.shutdownNow();}
}
}
Complexity analysis
Time: O(n) transfer work; wall time includes blocking.
Auxiliary space: O(capacity) pending items.
Test cases
- Empty work sequence.
- Interrupted producer.
- Consumer failure.
The supplied main asserts total 10 and bounds both future waits to five seconds.Common mistakes
- Using a sentinel that is also a legal work value.
- Swallowing interruption.
Key takeaways
- Bound queue capacity.
- Make completion explicit.
- Shutdown on both success and failure.
Follow-up challenges
- How would multiple consumers terminate?
- How would you persist accepted work across process failure?