parallel-in-scope interactive demo
A hands-on tour of the 0.5.0 core features: synchronous batches and one-shot groups on
borrowed executors, deadlines, fail-fast and await-all joins, request cancellation, frozen results,
execution exit, executor wait cycles, queue admission, and context propagation. Each section pairs a
simulation with the Java you would write. The library is io.github.monadrome:parallel-in-scope;
the quickstart shows the dependency and a first runnable example.
Feature index
Every core feature, with the section that demonstrates it.
- F01Composition root:
ParRuntimeand itsParentries - F02
ParIdlogical keys vs physical pools - F03Executor registration rules
- F04Batch:
Par.map - F05Sliding-window parallelism
- F06Join policy:
FAIL_FASTvsAWAIT_ALL(new in 0.5.0) - F07Batch with terminal combine:
Par.mapAndCombine - F08One-shot heterogeneous task group
- F09Typed keys and keyed reads:
TaskKey,GroupValues - F10Group terminal combine
- F11Per-member options:
TaskOptions - F12Adopting in-flight futures:
adopt - F13Frozen per-task result:
ImmediateResult - F14Typed termination vocabulary
- F15Scope-level termination:
ScopeTermination - F16Aggregate reads and the shared throw rule
- F17Deadlines and timeout inheritance
- F18Request cancellation:
cancelOn - F19Nested scopes: propagation and nested reads
- F20Cooperative cancellation:
Checkpoints - F21Caller interruption and borrowed threads
- F22Execution exit and bounded cleanup
- F23Exit observations:
TaskExitObservation - F24Runtime lifecycle and shutdown
- F25Executor wait report
- F26Queue admission:
SubmissionAwareBlockingQueue - F27Context propagation (TTL) and context executors
- F28Guava and
CompletableFutureinterop - F29Operational rules and integrations
- F30What changed in 0.5.0
- F31Testing code that uses the library
- F32Null-safe public API (JSpecify)
1. Runtime: build, work, close, await, shut down
Create one ParRuntime at the composition root. It maps each ParId to an executor it
borrows, hands out Par entries, and never shuts an executor down. There is no process-wide
instance: keep the runtime in your own field, or pass it or its Par entries to the components
that need them. Step through the lifecycle.
| Runtime | |
|---|---|
| Executors | |
inFlight() | |
snapshot() |
Snapshot numbers are illustrative. snapshot() samples its four counters independently,
so it is not linearizable: log it, do not branch on it.
2. Batch: Par.map and Par.mapAndCombine
map blocks the caller until every element has a frozen result and bounded cleanup is done. Every
element is prepared and bound to the deadline before submission starts; the sliding window
(parallelism) only decides when each prepared element enters the executor. The timeout is
mandatory: BatchOptions.timeout(name, duration) or inheritTimeout(name) inside a running task.
Event log
Java
Frozen result
The scope termination is derived from the frozen results, never from settle order: a
recorded failure outranks any cancellation, and the first failure in input order wins.
failedTaskResult() and orThrow() follow the same selection.
Rules this simulation follows
- Input. Order is kept; null or empty input returns an empty successful result; the input is
shallow-copied; a null element is rejected before any element runs; a mapper may return null. The mapper is a JDK
Function, so wrap checked exceptions (for example inUncheckedIOException). A null mapper is rejected before admission even for empty input, and a closed runtime throwsIllegalStateException. - Window.
parallelism(n)must be positive. Unset meansInteger.MAX_VALUE, capped at the batch size. After a cancellation the window stops submitting and unsubmitted elements never start. - FAIL_FAST (default): the first failure cancels every unfinished element, which ends
CANCELLEDwithABORTED_BY_FAIL_FAST. AWAIT_ALL: a failure ends only its element, and the window keeps going; the deadline,cancelOn, and an enclosing scope still cancel everything. The policy is per scope and never inherited. Prefer it to catch-and-fallback in the mapper: a broadcatchalso catches the cancellation a deadline orcancelOndelivers. - Deadline. Unfinished elements end with
DEADLINE_EXCEEDED. It is cooperative: it interrupts the worker but cannot abort a blocked socket read, so give every client its own connect and read timeouts. - cancelOn. Completing the source in any way cancels the whole scope, the combine included, and
interrupts running executions; a winning source records
CANCELLED_BY_CALLER. The library never completes or cancels the source. A source that is already complete prevents every execution from starting. After a normal return the link is severed, and the source can be reused for later executions. - Combine.
mapAndCombineruns the combine once, on its ownPar, only after every element succeeded, under the same deadline and cancellation. Otherwise itsterminalResult()recordsABORTED_BY_FAIL_FASTorDEADLINE_EXCEEDED(SUBMISSION_REJECTEDfor a rejected handoff). Its input must be non-empty. - Throw rule (
valuesOrThrow(),orThrow(),terminalValueOrThrow()): an unchecked failure is rethrown as-is, a checked one is wrapped inCompletionException, and pure cancellation throwsCancellationException. An emptyfailedTaskResult()after a pure timeout does not mean that every element succeeded. - Exit. A cancellation settles the result while the execution may still be unwinding. Once every
result settles, cleanup waits within
closeGrace, or the remaining deadline when it is unset. After a deadline nothing remains, so the wait is zero unlesscloseGraceis set. Zero grace does not wait.executionExitConfirmed()is a frozen fact at return: gate the release of shared resources on it, and keep task-local resources inside the execution (try-with-resources). A failure thrown after cancellation is logged, atFINEwhen it only acknowledges the cancellation and atWARNINGotherwise, and never changes the result.
Docs: Execute a batch · Let every element finish · Combine a batch · Scope termination · Cancel when a request completes · Interruption and cleanup
3. One-shot group: group(...).par(...).runAll()
A group coordinates a fixed set of named, differently typed operations. One fluent chain declares every member
with its typed TaskKey, its Par, and a Callable, then runAll() runs it
once and blocks. Declaration does no submission, deadline, timer, or TTL capture: the timeout starts at
runAll(). Only the creating thread may run the chain; stale stages, a second run, a foreign
Par, and duplicate names are rejected.
Event log
Java
Frozen TaskGroupResult
Rules this simulation follows
- Keys.
TaskKey.named(name)binds declaration and lookup to one type, soresultOf(userKey)is anImmediateResult<User>without a cast, and a mismatched type fails to compile. Equality is object identity: another key with the same name cannot read the slot, and an unknown key throwsIllegalArgumentException. Keys can be reused across runs and can carry generic types (TaskKey<List<Order>>). The result type does not widen with the member count. - Reads.
valuesOrThrow()returns the keyedGroupValuessnapshot (valueOf(key),valueOf(name),valueAt(index),size());resultOf(name)andresultAt(index)are the dynamic forms. - Combine.
combineandcombineValuesrun once, only after every member succeeded, with their own scoped execution and TTL snapshot.valuesis never null; the combine may return null and still succeed. It is not part ofGroupValues, of the name-based results, or of member positions.terminalResult()is null only when no combine is declared. A failed combine also fails the aggregated member values. AThreadPoolExecutorrejection handler may not run the combine inline. - TaskOptions.
TaskOptions.timeout(duration)orinheritTimeout()can shorten a member or combine deadline, capped by the group's. A member timeout cancels the whole group. There is no member-levelcancelOn: request cancellation belongs to the scope (GroupStart.cancelOn, before the first member).rejectEnqueueis the other member option. - adopt. From
runAll()on, the group owns each adopted future and cancels it withcancel(true)when it cancels unfinished members. Cancelling it yourself is a direct member cancellation. A successful future readsSUCCESS, a failed oneFAILEDwith its own throwable. Nothing is submitted and no TTL context is replayed for an adopted member. The group never closes a source's value: register resources with aClosingFuturepipeline and adoptfinishToFuture().adopt(key, producerPar, future)records an executor wait for the pool that completes the future. - Periodic futures are rejected: an
adoptcall typed withListenableScheduledFuturealways throwsUnsupportedOperationException, and a runtimeRunnableScheduledFuturewhoseisPeriodic()is true is rejected before the draft changes.
Docs: Execute a heterogeneous task group · Adopt futures already in flight
4. Frozen results: ImmediateResult, termination, exit observations
Every element and member ends as an ImmediateResult<T>: a shallowly immutable value-or-throwable
container, not a Future. Reads never block and never consume an interrupt. Its
termination() has three branches: SUCCESS, FAILED with a
FailureCause, and CANCELLED with a CancellationReason. A termination does not
say whether task code ran: treat every non-success as possibly run, and confirm execution exit before compensating.
Reads on ImmediateResult<Price>
asFuture(): read-only Guava adapter
Three-handler fold
TaskExitObservation<Price>
Vocabulary and interop
TaskTermination.Kind:SUCCESS,FAILED,CANCELLED.FailureCause.Kind:USER_CODE_FAILURE,SUBMISSION_REJECTED(an executor handoff failure, keeping the original cause).CancellationReason.Kind:CANCELLED_BY_CALLER,CANCELLED_BY_PARENT_SCOPE,DEADLINE_EXCEEDED,ABORTED_BY_FAIL_FAST,CANCELLED_BY_MEMBER.- Fail-fast siblings read
CANCELLED, notFAILED. The throwable stored for a cancellation is not always aCancellationException; it is normally aLeanCancellationExceptionnaming the reason. - Test doubles build results directly:
ImmediateResult.succeeded(value),ImmediateResult.failed(FailureCause.userCodeFailure(e)),ImmediateResult.cancelled(CancellationReason.deadlineExceeded(), new TimeoutException("stub")). - Batches expose
completions()in input order (a null entry means publication was not confirmed before return); groups exposemembers()by name andterminal()for the combine. Observations are frozen once and never change after return, so aggregate metrics on the caller. - There is no running library future to compose. Use
Futures.addCallbackorFutures.transformonasFuture(), and bridge toCompletableFuturewith a listener andFutures.getDone. External futures enter a group throughadopt.
ListenableFuture<Price> price = batch.results().get(0).asFuture();
CompletableFuture<Price> bridged = new CompletableFuture<>();
price.addListener(() -> {
try {
bridged.complete(Futures.getDone(price));
} catch (ExecutionException failure) {
bridged.completeExceptionally(failure.getCause());
}
}, executor);
Docs: Immediate results · Final observations · Guava and CompletableFuture interop
5. Nested scopes: cancellation flows down, failures flow up
A map, mapAndCombine, or runAll called inside a running execution inherits
cancellation and the minimum deadline through the execution context. Its result is already frozen when it returns,
so reading it never blocks.
Minimum deadline
Every deadline is capped by its parent's. Inheriting outside a library task fails
(IllegalArgumentException for a batch). Inside a task, Checkpoints.remaining() reports the budget
left: empty outside a task, Duration.ZERO once spent.
Docs: Cancellation and nested batches · Read nested results inside an execution
6. Cooperative cancellation and caller interruption
Cancellation settles the result at once and requests an interrupt on the running worker. Whether the execution
actually stops depends on the task body: a CPU loop needs Checkpoints.checkpoint(), a sleep needs
Checkpoints.checkSleep, and a catch block must not swallow cancellation. Pick a body and a cancellation
source. The batch has closeGrace(Duration.ofSeconds(1)); the work takes 2.4 s.
Checkpoints API and caller-thread rules
- The framework checks cancellation before every execution starts.
checkpoint()is a no-op outside a task;rawCheckpoint()works anywhere and honors the thread's interrupt flag without consuming it. Both throwLeanCancellationException, aCancellationExceptionwithout a stack trace. - Blocking adapters respond to the cancellation interrupt:
checkSleep,checkAwait,checkJoin,checkGet,checkTake,checkPut,checkTryAcquire,checkTryLock,checkAwaitTermination. - In a catch block call
Checkpoints.propagateCancellation(ex). For a plainInterruptedExceptioninside aFunction, restore the flag and rethrow it wrapped with its original cause. - The waits in
map,mapAndCombine, andrunAllignore interruption, also during bounded cleanup, and restore the flag on exit. Interrupting the caller does not cancel the work: wire an outside stop event intocancelOn. An already-interrupted caller runs normally, so check the flag first if it means stop.ParRuntime.awaitQuiescencestays interruptible. - A direct executor or
CallerRunsPolicymay run an execution inline on the caller; the entry interrupt state is restored afterwards. A cancellation interrupt never leaks into a later task that reuses the same worker thread.
SettableFuture<Void> stop = SettableFuture.create();
outerFuture.addListener(() -> {
if (outerFuture.isCancelled()) {
stop.set(null);
}
}, MoreExecutors.directExecutor());
par.map(ids, this::fetch, BatchOptions.timeout("fetch", timeout).cancelOn(stop));
7. Context propagation: TTL capture and context executors
Alibaba TransmittableThreadLocal values are captured when tasks are prepared on the calling thread and
replayed on the worker, then the worker's own bindings are restored. A combine gets its own snapshot. An ordinary
ThreadLocal, such as SLF4J's MDC, does not propagate.
Direct callbacks: which context does a listener see?
directContextExecutor() captures the current TTL at each execute call (changed in
0.5.0), so one instance serves many call sites. registrationContextExecutor() captures once, when it is
created: make one per request context and never a global singleton. Both restore the running thread's entry bindings
afterwards. Capture/replay/restore does not deep-copy bound values. For OpenTelemetry, capture
Context.current() on the calling thread and make it current inside each execution.
Docs: Integration recipes (MDC, direct callbacks, OpenTelemetry)
8. Executor wait report: spotting nested-pool deadlock risk
Every runtime records which registered pools synchronously wait on which: a task running on pool A that calls
map, mapAndCombine, or runAll onto pool B waits from A to B, if B is
starvation-prone. A ParId is only a lookup key: io and http below name one pool,
so the report shows them as one executor.
Blue outline: starvation-prone (buffering queue). The cached pool hands off through a zero-capacity queue, so waiting on it is never recorded.
ExecutorService ioPool = Executors.newFixedThreadPool(8);
ExecutorService dbPool = Executors.newFixedThreadPool(4);
ExecutorService elasticPool = Executors.newCachedThreadPool();
ParRuntime runtime = ParRuntime.builder()
.register(ParId.of("io"), ioPool)
.register(ParId.of("http"), ioPool) // a second key for the same pool
.register(ParId.of("db"), dbPool)
.register(ParId.of("elastic"), elasticPool)
.build();
// in a test, on a dedicated runtime:
service.handleRequest();
assertThat(runtime.executorWaitReport().cyclicComponents()).isEmpty();
The report accumulates for the runtime's lifetime: it is a structural risk signal, not a deadlock proof.
The first cycle, a self-loop included, logs one JUL WARNING from a runtime-owned thread. A component's
toString() is count-only. The report cannot see direct pool submissions, locks, unregistered executors,
or adopted futures without a producer Par. ParId.of(value) validates once: non-null,
non-blank, used verbatim.
9. Queue admission and executor registration
A ThreadPoolExecutor offers a task to its queue before it grows past its core size. With
SubmissionAwareBlockingQueue and rejectEnqueue(true) the queue refuses that offer, so the pool
grows a thread or runs its rejection handler instead of buffering. The tasks below run long, so every worker stays
busy while the batch is submitted.
build()rejects a directly registeredThreadPoolExecutorwithDiscardPolicyorDiscardOldestPolicy: they drop a task without running it or throwing, so its future would never complete.AbortPolicy(recorded asSUBMISSION_REJECTED) andCallerRunsPolicy(runs inline) are fine.- Register the physical pool. An executor the library cannot see through, such as a
listeningDecoratorwrapper orExecutors.newSingleThreadExecutor(), is accepted with a warning and blocking-risk detection disabled for it. A buffering queue makes a pool starvation-prone; a zero-capacity handoff (a cached pool) does not. rejectEnqueuedefaults tofalseand is read only bySubmissionAwareBlockingQueue; on any other queue it is inert, and the first such submission logs one warning. The general-purposeDrainingBlockingQueueandResizableBlockingQueuelive in the separateio.github.monadrome:blocking-queuesartifact.
Docs: Executor registration · Execute a batch · General-purpose queues
10. Operational rules and integrations
- Keep one
ParRuntimefor the application lifetime; close it at shutdown. - Executor ownership stays with the application: it shuts its pools down after
awaitQuiescence. - The library never purges queues. Cancelled entries can hold bounded-queue capacity until you call
ThreadPoolExecutor.purge()as executor-owner maintenance. - Give each batch a stable task name and add checkpoints to long CPU work.
- Use separate
Parentries for resources that need isolation, even when both are IO-bound. - Resilience4j and Sentinel: acquire the permit inside the execution around one downstream call, do not count cancellation as a downstream failure, and keep time and concurrency limits on the batch or group.
- Spring: register physical
ThreadPoolExecutorbeans, and close the runtime and await quiescence in the stop phase, before the executor beans are destroyed.
Docs: Operational rules · Purge cancelled queue entries · Resilience4j, Sentinel, and Spring
11. What changed in 0.5.0
JoinPolicy(FAIL_FAST,AWAIT_ALL) on batches and groups.- Typed termination is the only vocabulary, with the three-handler
ImmediateResult.fold. - Scope termination is derived from frozen results;
ScopeTerminationpayload accessors are read directly. - Keyed
GroupValuesandTaskGroupResult<R>; closedTaskId.UnitandTaskId.GroupRun. - Exit telemetry is named
TaskExitObservation. adoptoverloads typed withListenableScheduledFuturethrow, and periodicRunnableScheduledFuturesources are rejected.directContextExecutor()captures perexecute;registrationContextExecutor()captures at creation.SubmissionAwareBlockingQueuestays in core; the general queues moved toblocking-queues.- No global runtime slot: hold the runtime yourself.
Removed names and migration steps: CHANGELOG
12. Testing your code
There is no injectable clock, by design. Inject the timeout through your component's BatchOptions
instead, and block stubs on a latch rather than sleeping.
PriceClient hanging = sku -> {
Checkpoints.checkAwait(new CountDownLatch(1));
throw new AssertionError("released");
};
PriceService service = new PriceService(runtime.defaultPar(), hanging,
BatchOptions.timeout("price", Duration.ofMillis(50))
.closeGrace(Duration.ofSeconds(1)));
assertEquals(PriceService.UNKNOWN, service.price("sku-1"));
ImmediateResult<String> timedOut = ImmediateResult.cancelled(
CancellationReason.deadlineExceeded(), new TimeoutException("stub"));
Budget production = Checkpoints::remaining;
- Assert
TaskTermination.Kind.CANCELLEDandCancellationReason.Kind.DEADLINE_EXCEEDEDor the fallback value, never elapsed time. - Add
closeGracewhen assertingexecutionExitConfirmed(). - Read
Checkpoints.remaining()through your own interface so a test can substitute it. - Test result consumers without a runtime by returning fixed
ImmediateResultvalues. - Assert an empty
executorWaitReport().cyclicComponents()on a dedicated runtime.
13. Null-safe public API
Every core package is @NullMarked (JSpecify): parameters, returns, and type arguments are non-null
unless marked @Nullable. NullAway enforces this at compile time, and downstream NullAway, Kotlin, and
IntelliJ read the same annotations (jspecify is a compile-scope dependency).
public <T, R> TaskBatchResult<R> map(
@Nullable Collection<T> elements,
Function<? super T, ? extends @Nullable R> function,
BatchOptions options)
public List<@Nullable T> valuesOrThrow()
@Nullable R apply(V values) throws Exception; // Combiner<V, R>
- A null mapper or combine result is a legal success value.
- A null element is rejected before any element runs.
- A null input collection gives an empty successful result.
Docs: Nullability annotations