Middle · Trace · Pool leases, clearing and exception paths

Trace the portable program: what is guaranteed, and what does it not measure?

Think through your answer before opening the explanation.

Memory & GC

using System.Buffers;
var pool = ArrayPool<byte>.Shared;
var buffer = pool.Rent(8);
string report;
try
{
    buffer.AsSpan(0, 8).Clear();
    buffer[0] = 42;
    report = $"capacity-ok:{buffer.Length >= 8};first:{buffer[0]};logical:8";
}
finally { pool.Return(buffer, clearArray: true); }
Console.WriteLine(report);
Console.WriteLine("lease-ended:no-further-buffer-access");
Reveal answer and reasoning

The program rents at least eight bytes, clears the logical eight-byte region, writes 42 into the first element and creates a separate string report while the lease is active. The report records capacity-ok:True, first:42 and logical:8. A finally block returns the array with clearArray:true, so the return happens even if work inside try throws.

Only the independent string is printed after the lease ends. The program never reads the returned array to verify clearing and never asserts an exact rented capacity. The final line states that no further buffer access occurs. That discipline is part of the example's correctness. Printing buffer[0] after Return would be an invalid lesson even if the same value happened to remain in a local test.

A useful pool test records rental and return ownership through a small tracking pool or wrapper. Inject failure after rent, during processing and before creating the result. Confirm exactly one return on each accepted lease, no return when validation rejects before rent, and no outstanding consumers when the return occurs. Test cancellation while an async consumer is actually pending rather than only before entry.

The interactive workload budget keeps retained idle pool capacity separate from active payload storage. If your measured pool number already includes active rentals, do not add both quantities without adjusting the accounting. The model explicitly assumes nonoverlapping contributions. In a real process, shared arrays and pool buckets require careful attribution, and a type histogram alone may not identify which component currently owns a particular buffer.

What a strong answer covers

  • Rent promises at least the requested capacity, not an exact length.
  • Returning a buffer ends the lease even if the array remains reachable.
  • Pooling exchanges allocation work for retained capacity and ownership complexity.

Common pitfall

Reading a returned array to test clearing, or returning before an asynchronous borrower completes.

Follow-up questions

  1. Who releases a rented buffer when enqueue fails?
  2. How do you prevent double counting active rentals and idle pool capacity?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions