Course outline

Ruby / Integration: data, resources, runtime evidence, and trust / Lesson 21

Bounded queues and shutdown

Coordinate Ruby SizedQueue capacity, closure, and worker completion.

About 20 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Explain queue capacity and completion.
  • Test closure and worker ownership.
  • Design bounded queue backpressure, closure and item accounting.
  • Coordinate producer and consumer outcomes with explicit ownership.

Define queue ownership

A queue transfers work between producers and consumers. SizedQueue adds a capacity bound, so a producer may wait when the queue is full. Define who starts and joins workers, who closes the queue, and whether every submitted item must be processed. A queue’s synchronization protects its own operations; it does not automatically protect mutable objects shared through its entries.

Bound queued work

The first example uses a capacity-one queue sequentially: it pushes a value and then removes it. This illustrates the capacity and FIFO interface without relying on thread scheduling. In a concurrent pipeline, a blocking push needs a path to completion when consumers stop. Keep ownership of queued values clear, especially if a producer could mutate an object after enqueuing it.

ruby A bounded queue
queue = SizedQueue.new(1)
queue.push("job")
puts queue.pop
Expected output
job

The queued value is removed after insertion.

Close and drain

Closing a queue prevents later pushes while allowing buffered values to be removed. Once a closed queue is empty, a blocking pop returns nil. The second example closes after one value and shows both results. If nil is itself a valid queued value, that result is ambiguous; use an explicit message or another contract rather than treating every nil as proof of completion.

ruby A bounded queue
queue = SizedQueue.new(1)
queue.push("job")
queue.close
puts queue.pop
p queue.pop
Expected output
job
nil

The buffered value is returned before the empty closed queue returns nil.

Coordinate workers

Coordinate closure after all producers have finished, and join every worker before releasing state it can access. Decide how an exception in a producer reaches the owner and how waiting consumers are awakened. A bounded queue can apply backpressure, but it does not limit the size of each item or guarantee that a consumer completes its work successfully.

Test shutdown

Test normal completion with buffered values, an empty closed queue, and an attempted push after closure. Use controlled synchronization for concurrent tests instead of relying on exact sleep timing. Verify worker completion and the documented failure path as well as the values received. If the protocol permits nil messages, test that case separately from the end-of-stream signal.

Specify capacity and backpressure

A SizedQueue holds a bounded number of queued elements and coordinates its own push and pop operations. Its maximum must be positive. When capacity is full, a blocking producer may wait until space becomes available or the queue closes; a nonblocking call has a different failure contract that must be handled explicitly. State whether producers block, reject, retry or signal overload, and define what happens if consumers stop. A capacity in elements does not bound the byte size of each item, the number of active workers or the memory retained elsewhere.

Choose the bound from the application’s resource budget rather than assuming a universal value. A queue can apply backpressure, but it does not guarantee that a consumer successfully processes an item after popping it. Count accepted, queued, in-flight, completed and failed work separately when the service needs those distinctions. A synthetic capacity-one example illustrates an interface, not throughput, fairness, performance or an end-to-end delivery guarantee.

Define close, drain and message semantics

Closing a queue prevents subsequent pushes and allows buffered items to be removed. A blocking pop on a closed, empty queue returns nil. If nil is permitted as a data item, the same returned value is ambiguous without additional context; use a message envelope or prohibit nil data under a documented protocol. Do not silently change the meaning of a legitimate value into an end marker. A nonblocking pop has its own error behavior, so do not describe all empty-pop calls as returning nil.

The owner should coordinate closure after all producers have stopped submitting work under the normal completion policy. In Ruby’s documented SizedQueue behavior, closing also wakes waiting producers with ClosedQueueError. Decide how each producer reports that outcome, how consumers drain or discard buffered work, and who waits for all workers. Closing the queue is not equivalent to joining workers or proving that popped work completed successfully. Test a buffered item, empty closure, a later push and the declared nil-message policy separately.

This standalone sequential fixture uses non-nil message envelopes: two items fit the capacity, closure prevents a later push, and the consumer drains both before nil ends the loop. It models the queue contract only; no threads or runtime execution are claimed.

ruby Drain explicit messages and reject a late push
q = SizedQueue.new(2)
q.push({kind: :item, id: 'A'})
q.push({kind: :item, id: 'B'})
q.close
loop do
  message = q.pop
  break if message.nil?
  puts message.fetch(:id)
end
begin
  q.push({kind: :item, id: 'C'})
rescue ClosedQueueError
  puts 'closed'
end
Expected output
A
B
closed

The two queued IDs are read before the closed empty result, and the later push raises the handled closure error.

Own every worker outcome

A producer may fail before it finishes submitting, and a consumer may fail after removing an item. Define which owner observes each exception, whether other workers continue, and how queued and in-flight work is accounted for. A shutdown plan should stop or coordinate producers, close or otherwise signal consumers according to the protocol, collect worker outcomes and join owned threads before releasing shared state. An early consumer exit can leave producers blocked on a full queue unless the owner has an explicit wakeup or cancellation path.

A timeout means the owner stopped waiting; it does not prove a worker stopped or an external effect was rolled back. Preserve a request or item identifier, bound late-result storage, and define reconciliation or idempotent retry when a consumer might have committed an effect before reporting failure. Avoid forcing a production guarantee from a local queue: durable processing and cross-process coordination require an authoritative system with its own transaction and recovery contract.

Separate queue safety from item ownership

Queue synchronization protects its own internal operations, not arbitrary mutable state inside an item after it is enqueued. If a producer and consumer both retain a reference to the same array, either may change it unless the protocol prevents that. Choose immutable messages, a documented ownership transfer or an independent copy at the relevant depth. Copying only the outer envelope can leave nested arrays or strings shared; test the promised boundary rather than assuming enqueue creates a snapshot.

Avoid relying on incidental scheduling or exact print order. A controlled queue, barrier or acknowledgement can establish that a producer reached a known state before a test closes the queue or releases a consumer. Record accepted item IDs and terminal outcomes, not just messages printed by threads. A queue can preserve a transfer order for queued items while multiple consumers finish processing in a different order; define whether completion order matters independently of dequeue order.

Test the shutdown protocol, not one schedule

Build isolated cases for an empty queue, a full queue, buffered close and drain, push after close, a producer waiting at closure, consumer failure and early stop. Use explicit synchronization instead of sleeps to make the preconditions observable. Assert returned items, queue and worker states, exception outcomes and the final accounting invariant. If nil is allowed as data, test it separately from the closed-empty result; if an envelope is required, test the envelope’s item and completion variants.

The synthetic examples below are unexecuted because Ruby was unavailable in the authoring environment. Expected results follow Ruby 3.3 Queue and SizedQueue documentation and are not observed schedules, stress tests or benchmarks. Run them in an isolated compatible interpreter before claiming runtime evidence, then test the real engine, shutdown integration and any durable backend separately. A passing controlled schedule is valuable evidence but does not prove every possible interleaving or external effect safe.

20 worked examples

1. FIFO with two items

Problem: Remove two queued values in insertion order.

  1. The capacity permits both A and B to be queued.
  2. The first pop returns A and the second returns B.
ruby FIFO with two items
q = SizedQueue.new(2)
q.push('A')
q.push('B')
puts q.pop
puts q.pop
Expected output
A
B

Why this result follows: The sequential fixture demonstrates queue order without thread scheduling.

2. Capacity and size

Problem: Inspect the bound and current queued count.

  1. The queue maximum is three elements.
  2. After two pushes its current size is two.
ruby Capacity and size
q = SizedQueue.new(3)
q.push('A')
q.push('B')
puts q.max
puts q.size
Expected output
3
2

Why this result follows: Capacity and current occupancy are distinct measurements.

3. Nonblocking full push

Problem: Handle an attempted push to a full queue without waiting.

  1. The capacity-one queue already contains A.
  2. A nonblocking push of B raises ThreadError in this fixture.
ruby Nonblocking full push
q = SizedQueue.new(1)
q.push('A')
begin
  q.push('B', true)
rescue ThreadError
  puts 'full'
end
puts q.pop
Expected output
full
A

Why this result follows: The rejected push leaves the original queued item available.

4. Reject invalid capacity

Problem: Check the constructor’s positive-capacity requirement.

  1. The requested maximum is zero.
  2. SizedQueue rejects a nonpositive maximum with ArgumentError.
ruby Reject invalid capacity
begin
  SizedQueue.new(0)
rescue ArgumentError
  puts 'invalid capacity'
end
Expected output
invalid capacity

Why this result follows: The bound must be positive before work is queued.

5. Drain two buffered items

Problem: Close and remove all buffered items in order.

  1. Both items enter before closure.
  2. The closed queue returns A and B before its empty blocking pop returns nil.
ruby Drain two buffered items
q = SizedQueue.new(2)
q.push('A')
q.push('B')
q.close
puts q.pop
puts q.pop
p q.pop
Expected output
A
B
nil

Why this result follows: Closure prevents new pushes but does not erase buffered items.

6. Push after closure

Problem: Observe a rejected late push.

  1. The owner closes the queue before the push.
  2. The push raises ClosedQueueError and the handler records it.
ruby Push after closure
q = SizedQueue.new(1)
q.close
begin
  q.push('late')
rescue ClosedQueueError
  puts 'closed'
end
Expected output
closed

Why this result follows: The queue cannot accept a new item after closure.

7. Nil data ambiguity

Problem: Compare a queued nil with closed-empty completion.

  1. The first pop removes the queued nil value.
  2. After closure, the second blocking pop also returns nil.
ruby Nil data ambiguity
q = SizedQueue.new(1)
q.push(nil)
p q.pop
q.close
p q.pop
Expected output
nil
nil

Why this result follows: The same bare result cannot by itself distinguish data from completion.

8. Envelope for data

Problem: Represent nil payload inside a non-nil message.

  1. The queued hash is a non-nil item envelope.
  2. Its payload may be nil without being confused with the envelope itself.
ruby Envelope for data
q = SizedQueue.new(1)
q.push({kind: :item, payload: nil})
message = q.pop
p message[:kind]
p message[:payload]
Expected output
:item
nil

Why this result follows: A tagged envelope separates item identity from its nil payload.

9. Capacity is not completion

Problem: Separate dequeue from successful work.

  1. The consumer removes the queued item.
  2. The subsequent operation fails in the synthetic trace.
text Capacity is not completion
queue: item R1 popped
consumer: processing R1 failed
completion status: failure

Expected result: Report R1 as failed, not completed merely because it left the queue.

Why this result follows: A queue pop records transfer, not business success.

10. Item size is independent

Problem: Assess a capacity-one queue with a large item.

  1. The queue contains only one element.
  2. That element’s byte size is not bounded by the element count.
text Item size is independent
queue maximum: 1 item
queued item size: 10 MB
item-size policy: absent

Expected result: Add a separate item-size limit if the application requires one.

Why this result follows: A bound on count does not bound each item’s size.

11. Early consumer exit

Problem: Diagnose a producer waiting on a full queue after its consumer exits.

  1. The queue has reached capacity.
  2. No active consumer remains to remove an item and free space.
text Early consumer exit
capacity: 1
queued: A
producer: waiting to push B
consumer: exited

Expected result: The owner needs a coordinated close or cancellation path.

Why this result follows: Backpressure without a shutdown path can leave work blocked.

12. Waiting producer and close

Problem: Trace documented closure of a full SizedQueue.

  1. The producer is waiting to enqueue while the queue is full.
  2. Closing the queue wakes waiting enqueuers with ClosedQueueError.
text Waiting producer and close
capacity: 1
queued: A
producer: waiting to push B
owner: closes queue

Expected result: The producer must observe and handle ClosedQueueError.

Why this result follows: Closure wakes the waiting producer but does not mean B was accepted.

13. Close after producers finish

Problem: Define a normal closure ordering for two producers.

  1. Both producers own their submissions until they finish.
  2. The coordinator closes the queue only after collecting their completion.
text Close after producers finish
producer A: finished
producer B: finished
coordinator: close queue
consumers: drain and finish

Expected result: Close after both producers and join consumers after draining.

Why this result follows: Closure ownership prevents normal producers from pushing after close.

14. Producer failure before close

Problem: Account for a failed producer and waiting consumers.

  1. Producer A fails before finishing its submissions.
  2. Consumers still need a wakeup and the owner must collect the failure.
text Producer failure before close
producer A: exception
producer B: stopped by policy
consumers: waiting
queue owner: coordinator

Expected result: Report A’s failure, coordinate closure and join all owned workers.

Why this result follows: A failure path must release waiters and preserve the error.

15. Consumer fails after pop

Problem: Track an item that left the queue but did not complete.

  1. R1 is no longer buffered after pop.
  2. The consumer then raises before reporting successful processing.
text Consumer fails after pop
queue: R1 popped
consumer: exception
R1 terminal result: unknown

Expected result: Record R1 as failed or ambiguous under the processing contract.

Why this result follows: Queue transfer does not prove the business effect completed.

16. Join before releasing state

Problem: Keep shared state alive until workers terminate.

  1. The worker may still access the shared accumulator.
  2. The owner waits for its terminal outcome before releasing that state.
text Join before releasing state
worker: active
shared accumulator: in use
owner: join worker, then release

Expected result: Release shared state only after the owned worker has finished.

Why this result follows: Joining makes the lifetime boundary explicit.

17. Mutable message alias

Problem: Review a queued array still held by its producer.

  1. The producer and consumer may share the same mutable array reference.
  2. A later producer append can change what the consumer observes.
text Mutable message alias
producer message: array ['A']
producer enqueues message
producer retains alias and appends 'B'

Expected result: Define immutable, copied or transferred ownership before enqueueing.

Why this result follows: Queue synchronization does not protect arbitrary item mutation.

18. Dequeue versus completion order

Problem: Compare a queue’s transfer order with two consumers finishing.

  1. A is popped before B in the modeled trace.
  2. Consumer B finishes its work before the slower consumer A.
text Dequeue versus completion order
dequeue order: A, B
completion order: B, A
consumer count: 2

Expected result: The trace is consistent with FIFO dequeue and different completion order.

Why this result follows: FIFO transfer does not serialize independent processing durations.

19. Timeout after dequeue

Problem: Reconcile a timed-out item whose external effect is unknown.

  1. The worker removed R2 from the queue.
  2. Its remote operation timed out without an authoritative result.
text Timeout after dequeue
item: R2
queue state: popped
remote outcome: unknown

Expected result: Retain R2’s identity and reconcile before retrying.

Why this result follows: A queue timeout cannot prove a remote effect did not commit.

20. Accounting at shutdown

Problem: Check whether every accepted item has a terminal outcome.

  1. The owner accepted three identified items.
  2. Only two terminal outcomes have been reported.
text Accounting at shutdown
accepted: A, B, C
completed: A
failed: B
C outcome: missing

Expected result: Keep shutdown incomplete until C is resolved or explicitly reconciled.

Why this result follows: Worker joins and item accounting answer complementary questions.

Common errors and fixes

A producer remains blocked

Why it happens
The queue is full and consumers have stopped.
How to fix it
Provide a coordinated shutdown path.
Prevent it next time
Test early consumer exit.

A push fails after closure

Why it happens
The queue closed while a producer was still active.
How to fix it
Close after all producers finish.
Prevent it next time
Document closure ownership.

A nil item is mistaken for completion

Why it happens
The protocol permits nil as both data and an empty-closed result.
How to fix it
Use an unambiguous message contract.
Prevent it next time
Test nil data and closure separately.

20 practice exercises

1. What does the second example print after job?

Show hint

After the buffered job is removed, inspect the queue’s closed and empty state.

Show worked solution

It prints nil because the queue is closed and empty after the buffered item is removed.

The first pop returns job; the next blocking pop returns nil because the queue is closed and empty. If nil is allowed as data, the application needs an unambiguous message protocol rather than relying on the value alone.

Check your solution

  • The second printed result is nil.
  • The explanation identifies both closure and emptiness.

2. Why must workers be joined before shared state is released?

Show hint

A worker can still use shared objects after its caller stops waiting.

Show worked solution

A worker may still access that state until it finishes. Joining makes completion explicit.

Join owned workers before releasing state they may access, and collect their errors and results under the shutdown policy. Queue closure alone does not establish that processing has completed.

Check your solution

  • The shared state remains valid until worker completion.
  • Worker outcomes are collected separately from queue closure.

3. A capacity-two queue contains A then B. Producer C attempts a nonblocking push while producer D waits; a coordinated consumer pops A and then D succeeds. Classify accepted and rejected work.

Show hint

The two producer policies have different outcomes at full capacity.

Show worked solution

C receives the full-queue failure and is not accepted. After the coordinated pop frees one slot, D pushes successfully; the queue then contains B followed by D. Test the preconditions with signals rather than guessing which producer runs first.

Check your solution

  • C is rejected and D is accepted only after space is freed.
  • The remaining dequeue order is B then D.

4. A closed queue contains two tagged item messages: one payload is nil and the other is false. Design a consumer that processes both before recognizing closed-empty completion.

Show hint

Test the envelope itself, not the truthiness of its payload.

Show worked solution

Pop each non-nil envelope and dispatch by its kind, preserving nil and false as distinct payloads. Only the later bare nil from the drained closed queue ends the loop; reject malformed envelopes under a separate policy.

Check your solution

  • Both nil and false payloads are processed as items.
  • The consumer stops only on the later closed-empty result.

5. Two producers share a queue; one finishes while the other is still submitting. Define who closes and a test for late submissions.

Show hint

Closure must follow all producers under the normal policy.

Show worked solution

Have a coordinator observe both producer completions before closing the queue, then let consumers drain and join. Use controlled signals to keep the second producer active and verify it can submit before closure; separately test failure shutdown.

Check your solution

  • The first producer finishing does not close the queue early.
  • The second producer’s accepted work is accounted for.

6. A capacity-one queue holds A while consumer X fails processing an earlier item. Producers C and D are both waiting to enqueue. Design failure shutdown and accounting.

Show hint

The in-flight item, buffered item and two unaccepted pushes are distinct.

Show worked solution

Have the owner observe X’s failure, close the queue to wake the waiting producers under the documented Ruby contract, and collect both closure errors. Record X’s item as failed or ambiguous, A as buffered for the drain or discard policy, and C and D as not accepted; join every worker.

Check your solution

  • The in-flight and buffered items have separate outcomes.
  • Both waiting producers terminate and C and D are not counted as accepted.

7. Consumer one popped A and confirmed its remote write committed; consumer two popped B but failed after a timeout with remote state unknown. Design item accounting and retry decisions.

Show hint

Confirmed and ambiguous effects require different recovery decisions.

Show worked solution

Record A as completed and do not repeat it blindly. Record B as ambiguous, collect the worker error and reconcile B by its stable operation ID before any retry under the service contract; keep both outcomes visible in the batch report.

Check your solution

  • A is reported completed and is not blindly repeated.
  • B is reconciled before a retry decision.

8. A queue allows three items, each at most 1,024 bytes; queued plus in-flight bytes must stay at most 2,048. A queued item uses 900 bytes and an in-flight item uses 800. Classify new items of 400 and 300 bytes, considered separately.

Show hint

The combined memory budget includes in-flight work, not only queue slots.

Show worked solution

The current total is 1,700 bytes. Adding 400 would reach 2,100 and must be rejected or delayed; adding 300 reaches 2,000 and fits both the per-item and combined limits. Test each candidate from the same initial state.

Check your solution

  • The 400-byte candidate exceeds the combined limit.
  • The 300-byte candidate fits the stated limits.

9. A producer enqueues an envelope containing an array of mutable labels. The consumer needs a creation-time snapshot, while the producer must keep editing its own labels. Design a two-level copy and tests.

Show hint

Copy the known nested array and strings before enqueueing.

Show worked solution

Construct a new envelope containing a new array of duplicated strings, and enqueue that snapshot. After enqueueing, append a source label and edit an existing source string; assert the consumer’s envelope retains its original count and text, while the producer’s originals remain mutable.

Check your solution

  • The snapshot excludes both the later append and string edit.
  • The producer’s original array and strings remain editable.

10. Two consumers dequeue A then B; B completes first. The product requires ordered commits and A can fail. Design a protocol for success and failure.

Show hint

FIFO dequeue alone does not enforce commit order.

Show worked solution

Buffer B’s result until A has a terminal outcome, then commit in the documented order if policy permits. If A fails, apply an explicit abort or recovery policy before committing B; test both success and failure with controlled coordination.

Check your solution

  • On success, commits occur A then B despite B finishing first.
  • An A failure follows the stated policy without silently committing B out of order.

11. A closed capacity-two queue contains two tagged items A and B. Two consumers drain it and may finish in either order. Define accounting without assuming which consumer receives each item.

Show hint

Queue transfer order and worker completion order are different observations.

Show worked solution

Assert each accepted item is popped exactly once, both consumers eventually observe closed-empty completion under the protocol, and each item receives a terminal processing outcome. Do not assert a particular consumer assignment or completion order without additional coordination.

Check your solution

  • A and B are each accounted for exactly once.
  • Both consumers terminate without an assumed completion order.

12. A nonblocking pop is attempted on an empty queue. Define the error path and contrast it with blocking pop after closure.

Show hint

The nonblocking flag changes empty-queue behavior.

Show worked solution

Handle the documented ThreadError for an empty nonblocking pop rather than interpreting it as a data item. Separately, a blocking pop on a closed empty queue returns nil; test both calls under the selected Ruby version.

Check your solution

  • The nonblocking empty pop has an explicit error outcome.
  • The closed-empty blocking pop returns nil.

13. A capacity-one queue holds A. Producer B is waiting to push; producer C makes a nonblocking push and receives a full error. The owner then closes the queue. Account for all three items.

Show hint

The waiting and nonblocking producer paths fail for different reasons.

Show worked solution

C is not accepted after the full error. Closing wakes waiting B with ClosedQueueError, so B is not accepted either; A remains buffered for the declared drain or discard policy. Observe both producer outcomes and join them.

Check your solution

  • B and C are unaccepted for their respective documented reasons.
  • A remains separately accounted for as buffered work.

14. Five accepted items have states: A and B completed, C failed, D is still running and E is buffered. Two workers are still active. Define the shutdown accounting and release condition.

Show hint

Item state and worker lifetime must both reach the documented terminal policy.

Show worked solution

Report A and B completed and C failed; retain ownership of D and E for completion, cancellation or explicit reconciliation. Coordinate closure and join both active workers before releasing shared resources, and do not call shutdown complete while D or E lacks a terminal disposition.

Check your solution

  • All five IDs appear in distinct accounted states.
  • Shared resources remain valid until workers terminate and D and E are resolved.

15. Two attempts for item R2 share one operation ID: the first is confirmed committed and the second times out. Design late-result and duplicate-handling checks.

Show hint

Both attempts refer to one logical external effect.

Show worked solution

Record both attempt outcomes under the same stable ID, retain the late-result owner and consult authoritative state. The confirmed commit must not be repeated; test a duplicate retry against the documented idempotency contract and bound pending-result retention.

Check your solution

  • The committed effect is not applied twice.
  • The timed-out attempt has an owned reconciliation path and bounded retention.

16. A test uses sleep to assume the producer is blocked before closure. Design controlled synchronization for the precondition.

Show hint

The test needs evidence that the desired state has been reached.

Show worked solution

Use a supported signal, barrier or queue handshake to arrange and observe the producer’s precondition before the coordinator closes the queue. Then assert the documented closure outcome and join the worker; avoid a guessed sleep duration.

Check your solution

  • The test coordinates the precondition explicitly.
  • The producer outcome is observed and the worker joined.

17. A producer fails after submitting A but before submitting B. Define a report for accepted, unsubmitted and worker-failure states.

Show hint

The queue and worker outcomes must both be retained.

Show worked solution

Record A as accepted and track its processing outcome, record B as unsubmitted, and propagate or report the producer failure. Coordinate queue closure and join consumers according to policy instead of reporting the batch as fully submitted.

Check your solution

  • A and B receive distinct accounting states.
  • The producer failure remains visible.

18. Two consumers use tagged stop messages instead of interpreting nil as data. Producers are finished, and all accepted items precede the stop messages. Design a shutdown protocol and test.

Show hint

Each consumer needs an unambiguous termination path after the data sequence.

Show worked solution

Enqueue one explicit stop envelope per consumer only after producers finish and accepted items are submitted. Verify both consumers exit, every item has a terminal outcome and no later data is accepted; define how queue closure and worker joins complete the lifecycle.

Check your solution

  • Each of the two consumers receives a termination path.
  • Every accepted data item is accounted for before shutdown completes.

19. A queue is bounded and all local tests pass. State which production guarantees remain unproven.

Show hint

Local queue synchronization has a limited scope.

Show worked solution

The tests do not establish durable delivery, cross-process coordination, remote transaction rollback or every possible schedule. Define those guarantees at their actual boundaries and run separately authorized integration and failure tests.

Check your solution

  • The local test scope is stated accurately.
  • Durability and cross-process behavior remain separate claims.

20. A capacity-one queue has producer A submitting a1 then a2, producer B submitting b1, and one consumer. The contract requires a terminal outcome for every accepted item; B may fail after b1 is accepted. Design a controlled acceptance matrix.

Show hint

Separate acceptance, processing outcome, closure and worker completion.

Show worked solution

Test a normal run with all three items, a controlled full-queue wait, B failing after b1 is accepted, and consumer failure after a pop. Record which pushes succeeded and each accepted item’s terminal disposition; coordinate closure and join every worker without assuming an interleaving or completion order.

Check your solution

  • The normal case accounts for a1, a2 and b1 exactly once.
  • Failure cases report accepted, unsubmitted and in-flight items and join all workers.

Key takeaways

  • Bounded capacity needs a shutdown path.
  • Coordinate closure, failures, and worker completion.
  • Queue capacity bounds queued elements, not item size or successful processing.
  • Close prevents pushes and allows buffered items to drain.
  • Join workers and reconcile every accepted item before releasing owned state.

Official references