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.

1. Runtime: build, work, close, await, shut down

F01 composition rootF24 lifecycle

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.

Docs: Build the execution topology · Application shutdown

2. Batch: Par.map and Par.mapAndCombine

F04 mapF05 sliding windowF06 join policyF07 mapAndCombineF15 scope terminationF16 throw ruleF17 deadlinesF18 cancelOnF22 execution exit

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.

Element durations are fixed (300 to 700 ms; 2.5 s for the blocked read). Changing a setting resets the run.
t = 0 ms

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 in UncheckedIOException). A null mapper is rejected before admission even for empty input, and a closed runtime throws IllegalStateException.
  • Window. parallelism(n) must be positive. Unset means Integer.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 CANCELLED with ABORTED_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 broad catch also catches the cancellation a deadline or cancelOn delivers.
  • 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. mapAndCombine runs the combine once, on its own Par, only after every element succeeded, under the same deadline and cancellation. Otherwise its terminalResult() records ABORTED_BY_FAIL_FAST or DEADLINE_EXCEEDED (SUBMISSION_REJECTED for 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 in CompletionException, and pure cancellation throws CancellationException. An empty failedTaskResult() 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 unless closeGrace is 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, at FINE when it only acknowledges the cancellation and at WARNING otherwise, 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()

F08 groupF09 TaskKey and GroupValuesF10 combineF11 TaskOptionsF12 adopt

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.

Group timeout 2 s. user takes 400 ms, account 700 ms, the adopted orders future 600 ms, the combine 200 ms.
t = 0 ms

Event log

Java

Frozen TaskGroupResult

Rules this simulation follows
  • Keys. TaskKey.named(name) binds declaration and lookup to one type, so resultOf(userKey) is an ImmediateResult<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 throws IllegalArgumentException. 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 keyed GroupValues snapshot (valueOf(key), valueOf(name), valueAt(index), size()); resultOf(name) and resultAt(index) are the dynamic forms.
  • Combine. combine and combineValues run once, only after every member succeeded, with their own scoped execution and TTL snapshot. values is never null; the combine may return null and still succeed. It is not part of GroupValues, 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. A ThreadPoolExecutor rejection handler may not run the combine inline.
  • TaskOptions. TaskOptions.timeout(duration) or inheritTimeout() can shorten a member or combine deadline, capped by the group's. A member timeout cancels the whole group. There is no member-level cancelOn: request cancellation belongs to the scope (GroupStart.cancelOn, before the first member). rejectEnqueue is the other member option.
  • adopt. From runAll() on, the group owns each adopted future and cancels it with cancel(true) when it cancels unfinished members. Cancelling it yourself is a direct member cancellation. A successful future reads SUCCESS, a failed one FAILED with 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 a ClosingFuture pipeline and adopt finishToFuture(). adopt(key, producerPar, future) records an executor wait for the pool that completes the future.
  • Periodic futures are rejected: an adopt call typed with ListenableScheduledFuture always throws UnsupportedOperationException, and a runtime RunnableScheduledFuture whose isPeriodic() 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

F13 ImmediateResultF14 termination vocabularyF23 TaskExitObservationF28 Guava interop

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, not FAILED. The throwable stored for a cancellation is not always a CancellationException; it is normally a LeanCancellationException naming 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 expose members() by name and terminal() 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.addCallback or Futures.transform on asFuture(), and bridge to CompletableFuture with a listener and Futures.getDone. External futures enter a group through adopt.
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

F19 nested scopesF17 minimum deadline

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

    F20 CheckpointsF21 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.

    t = 0 ms
    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 throw LeanCancellationException, a CancellationException without 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 plain InterruptedException inside a Function, restore the flag and rethrow it wrapped with its original cause.
    • The waits in map, mapAndCombine, and runAll ignore interruption, also during bounded cleanup, and restore the flag on exit. Interrupting the caller does not cancel the work: wire an outside stop event into cancelOn. An already-interrupted caller runs normally, so check the flag first if it means stop. ParRuntime.awaitQuiescence stays interruptible.
    • A direct executor or CallerRunsPolicy may 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));

    Docs: Cooperative cancellation · Interruption and cleanup

    7. Context propagation: TTL capture and context executors

    F27 TTL and ContextExecutors

    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

    F25 executorWaitReportF02 ParId vs pool

    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.

    Docs: Diagnostics: observe nested work

    9. Queue admission and executor registration

    F26 SubmissionAwareBlockingQueueF03 registration rules

    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.

    Docs: Executor registration · Execute a batch · General-purpose queues

    10. Operational rules and integrations

    • Keep one ParRuntime for 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 Par entries 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 ThreadPoolExecutor beans, 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; ScopeTermination payload accessors are read directly.
    • Keyed GroupValues and TaskGroupResult<R>; closed TaskId.Unit and TaskId.GroupRun.
    • Exit telemetry is named TaskExitObservation.
    • adopt overloads typed with ListenableScheduledFuture throw, and periodic RunnableScheduledFuture sources are rejected.
    • directContextExecutor() captures per execute; registrationContextExecutor() captures at creation.
    • SubmissionAwareBlockingQueue stays in core; the general queues moved to blocking-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.CANCELLED and CancellationReason.Kind.DEADLINE_EXCEEDED or the fallback value, never elapsed time.
    • Add closeGrace when asserting executionExitConfirmed().
    • Read Checkpoints.remaining() through your own interface so a test can substitute it.
    • Test result consumers without a runtime by returning fixed ImmediateResult values.
    • Assert an empty executorWaitReport().cyclicComponents() on a dedicated runtime.

    Docs: Testing code that uses the library

    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