← All Exercises

Producer-Consumer with a BlockingQueue

advancedjava~20min

Background

Blocking queues handle backpressure and handoff without explicit locks. Poison pills are a simple, deterministic shutdown signal for a fixed set of workers.

Problem

Build a producer-consumer pipeline with a bounded queue. The producer emits 1 through 10, two consumers sum them, and poison values stop both workers without losing items.

Input

No required input. An optional first argument sets the item count, defaulting to 10, and must be a positive integer.

Output

A line consumed=<n> sum=<n>, followed by a check that throws if the count or sum differs from the expected arithmetic-series totals.

Sample tests

Sample 1

Input: run the program with the default item count 10
Expected: consumed=10 sum=55

Sample 2

Input: run with argument 4
Expected: consumed=4 sum=10

Your solution

Learning objective

Use a bounded BlockingQueue, poison-pill termination, an executor, and atomic aggregation for a race-free pipeline.