Skip to content

Commit ef68624

Browse files
ctruedenclaude
andcommitted
scijava-concurrent: let cancellation survive a parallel section
Interrupting a thread that had farmed work out to a TaskExecutor cancelled the workers but lost the cancellation at the caller: the InterruptedException was wrapped in a plain RuntimeException, and the flag it cleared on the way out was never restored. Code further up the stack could not tell cancellation from failure, and an outer op polling Progress.checkCancellation() would never see it. Half the propagation was already correct and worth noting, since it is easy to reimplement by accident: ExecutorService.invokeAll cancels its unfinished tasks when the awaiting thread is interrupted, and cancels them with interruption. The missing half was the caller's own flag. The two call sites now separate InterruptedException from ExecutionException, restore the flag, and throw CancellationException -- the same type Progress.checkCancellation() throws, so one exception type means "cancelled" throughout. The test fails against the previous code with exactly the symptom described: "expected CancellationException, got: java.lang.RuntimeException: java.lang.InterruptedException". Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gJpzGd3ksbME4CN6Tu2ni
1 parent ea1ac3c commit ef68624

3 files changed

Lines changed: 138 additions & 6 deletions

File tree

‎docs/migration-plan.md‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -272,9 +272,14 @@ reporting progress.
272272
only completes the future exceptionally. Expose `ExecutorService` futures
273273
where cancellation must reach a compute loop.
274274
- The interrupt flag is thread-bound and **does not inherit**, unlike
275-
`Progress`, which is an `InheritableThreadLocal`. So `Parallelization` and
276-
`TaskExecutor` must propagate cancellation to worker futures deliberately.
277-
That is the one piece of real work this design implies.
275+
`Progress`, which is an `InheritableThreadLocal`. Propagation to workers is
276+
therefore deliberate. In `TaskExecutors` most of it was already there:
277+
`ExecutorService.invokeAll` cancels its unfinished tasks — interrupting
278+
them — when the awaiting thread is interrupted. What was missing was the
279+
other half: the `InterruptedException` was wrapped in a plain
280+
`RuntimeException` and **the caller's own flag was never restored**, so
281+
cancellation died at that layer. It now restores the flag and throws
282+
`CancellationException`.
278283
- Plain `InputStream`/`FileInputStream` reads are not interruptible; only NIO
279284
channels are. Blocking I/O therefore aborts between operations, not during
280285
one.
@@ -296,7 +301,9 @@ it stands**. In-process: interruption. Across processes: an explicit protocol.
296301
submit to an executor, and cancellation is `future.cancel(true)`.
297302
3. `Progress.update()` checks for interruption and throws
298303
`CancellationException`.
299-
4. `Parallelization` propagates cancellation to its workers.
304+
4. `Parallelization` propagates cancellation to its workers: `TaskExecutors`
305+
restores the interrupt flag and throws `CancellationException` rather than
306+
swallowing the interrupt in a `RuntimeException`.
300307
5. `DataHandles.copy` checks once per block and throws
301308
`java.io.InterruptedIOException`, which is an `IOException` — so it fits
302309
the existing signature — and whose `bytesTransferred` field reports the

‎scijava-concurrent/src/main/java/org/scijava/concurrent/TaskExecutors.java‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
import java.util.List;
3737
import java.util.concurrent.AbstractExecutorService;
3838
import java.util.concurrent.Callable;
39+
import java.util.concurrent.CancellationException;
3940
import java.util.concurrent.ExecutionException;
4041
import java.util.concurrent.ExecutorService;
4142
import java.util.concurrent.Executors;
@@ -260,7 +261,10 @@ public <T, R> List<R> forEachApply(List<? extends T> parameters,
260261
results.add(future.get());
261262
return results;
262263
}
263-
catch (InterruptedException | ExecutionException e) {
264+
catch (final InterruptedException e) {
265+
throw cancelled();
266+
}
267+
catch (final ExecutionException e) {
264268
throw unwrapExecutionException(e);
265269
}
266270
}
@@ -271,7 +275,10 @@ private void invokeAllIgnoreResults(final List<Callable<Object>> callables) {
271275
for (var future : futures)
272276
future.get();
273277
}
274-
catch (InterruptedException | ExecutionException e) {
278+
catch (final InterruptedException e) {
279+
throw cancelled();
280+
}
281+
catch (final ExecutionException e) {
275282
throw unwrapExecutionException(e);
276283
}
277284
}
@@ -282,6 +289,22 @@ private void invokeAllIgnoreResults(final List<Callable<Object>> callables) {
282289
* read. This method unwraps the {@link ExecutionException} and thereby
283290
* reveals the original exception, and ensures it's complete stack trace.
284291
*/
292+
/**
293+
* Reports that this thread was cancelled while awaiting its workers.
294+
* <p>
295+
* NB: {@link ExecutorService#invokeAll} has already cancelled the
296+
* unfinished tasks, which interrupts their threads. What is left is this
297+
* thread's own flag, which {@link InterruptedException} cleared on its
298+
* way out; restoring it is what lets code further up the stack see that
299+
* the work was cancelled rather than that it failed.
300+
* </p>
301+
*/
302+
private CancellationException cancelled() {
303+
Thread.currentThread().interrupt();
304+
return new CancellationException("Cancelled: " + Thread.currentThread()
305+
.getName());
306+
}
307+
285308
private RuntimeException unwrapExecutionException(Throwable e) {
286309
if (e instanceof ExecutionException) {
287310
final var cause = e.getCause();
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/*-
2+
* #%L
3+
* SciJava library facilitating consistent parallel processing.
4+
* %%
5+
* Copyright (C) 2021 - 2025 SciJava developers.
6+
* %%
7+
* Redistribution and use in source and binary forms, with or without
8+
* modification, are permitted provided that the following conditions are met:
9+
*
10+
* 1. Redistributions of source code must retain the above copyright notice,
11+
* this list of conditions and the following disclaimer.
12+
* 2. Redistributions in binary form must reproduce the above copyright notice,
13+
* this list of conditions and the following disclaimer in the documentation
14+
* and/or other materials provided with the distribution.
15+
*
16+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
20+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26+
* POSSIBILITY OF SUCH DAMAGE.
27+
* #L%
28+
*/
29+
30+
package org.scijava.concurrent;
31+
32+
import static org.junit.jupiter.api.Assertions.assertNotNull;
33+
import static org.junit.jupiter.api.Assertions.assertTrue;
34+
35+
import java.util.List;
36+
import java.util.concurrent.CancellationException;
37+
import java.util.concurrent.CountDownLatch;
38+
import java.util.concurrent.TimeUnit;
39+
import java.util.concurrent.atomic.AtomicBoolean;
40+
import java.util.concurrent.atomic.AtomicInteger;
41+
import java.util.concurrent.atomic.AtomicReference;
42+
43+
import org.junit.jupiter.api.Test;
44+
45+
/**
46+
* Tests that cancelling a thread which farmed work out to a
47+
* {@link TaskExecutor} reaches the workers, and is still visible afterward.
48+
* <p>
49+
* The interrupt flag does not inherit to worker threads, so this propagation
50+
* is deliberate rather than automatic.
51+
* </p>
52+
*
53+
* @author Curtis Rueden
54+
*/
55+
public class CancellationTest {
56+
57+
/**
58+
* Interrupting the calling thread cancels the workers, surfaces as a
59+
* {@link CancellationException}, and leaves the caller's interrupt flag set.
60+
*/
61+
@Test
62+
public void testInterruptionReachesWorkers() throws Exception {
63+
final CountDownLatch allStarted = new CountDownLatch(4);
64+
final AtomicInteger interruptedWorkers = new AtomicInteger();
65+
final AtomicReference<RuntimeException> thrown = new AtomicReference<>();
66+
final AtomicBoolean flagStillSet = new AtomicBoolean();
67+
68+
final Thread caller = new Thread(() -> {
69+
try (final TaskExecutor executor = TaskExecutors.fixedThreadPool(4)) {
70+
executor.forEach(List.of(1, 2, 3, 4), i -> {
71+
allStarted.countDown();
72+
try {
73+
// NB: long enough that the interrupt lands mid-flight.
74+
Thread.sleep(30_000);
75+
}
76+
catch (final InterruptedException exc) {
77+
interruptedWorkers.incrementAndGet();
78+
Thread.currentThread().interrupt();
79+
}
80+
});
81+
}
82+
catch (final RuntimeException exc) {
83+
thrown.set(exc);
84+
flagStillSet.set(Thread.currentThread().isInterrupted());
85+
}
86+
});
87+
caller.start();
88+
assertTrue(allStarted.await(10, TimeUnit.SECONDS), "workers never started");
89+
90+
caller.interrupt();
91+
caller.join(10_000);
92+
93+
final RuntimeException exc = thrown.get();
94+
assertNotNull(exc, "the caller was not cancelled");
95+
assertTrue(exc instanceof CancellationException,
96+
"expected CancellationException, got: " + exc);
97+
assertTrue(flagStillSet.get(),
98+
"the caller's interrupt flag must be restored");
99+
assertTrue(interruptedWorkers.get() > 0,
100+
"cancellation never reached the workers");
101+
}
102+
}

0 commit comments

Comments
 (0)