|
| 1 | +--- |
| 2 | +id: 10f4499a-362f-4aa9-900a-14b34732b147 |
| 3 | +slug: "thread-stop-to-cooperative-cancellation" |
| 4 | +title: "Unsafe thread termination to cooperative cancellation" |
| 5 | +category: "concurrency" |
| 6 | +difficulty: "advanced" |
| 7 | +jdkVersion: "5" |
| 8 | +oldLabel: "Forced thread termination" |
| 9 | +modernLabel: "Future cancellation" |
| 10 | +oldApproach: "Thread.stop()" |
| 11 | +modernApproach: "Future.cancel(true)" |
| 12 | +oldCode: |- |
| 13 | + Thread worker = new Thread(this::runTask); |
| 14 | + worker.start(); |
| 15 | +
|
| 16 | + // May stop the thread while shared state is inconsistent. |
| 17 | + worker.stop(); |
| 18 | +modernCode: |- |
| 19 | + Future<?> worker = executor.submit(this::runTask); |
| 20 | +
|
| 21 | + // Requests interruption; the task must cooperate. |
| 22 | + worker.cancel(true); |
| 23 | +summary: "Replace Thread.stop() and ad hoc shared flags with interruption-aware task cancellation." |
| 24 | +explanation: "Thread.stop() can terminate code while it owns monitors or is updating shared\ |
| 25 | + \ state, leaving objects damaged. Modern cancellation is cooperative: cancel the Future\ |
| 26 | + \ with interruption, propagate InterruptedException where possible, restore interrupt status\ |
| 27 | + \ when it cannot be propagated, and design the task to reach safe cancellation points." |
| 28 | +whyModernWins: |
| 29 | +- icon: "🛡" |
| 30 | + title: "Preserves invariants" |
| 31 | + desc: "Tasks stop only at code paths designed for cancellation." |
| 32 | +- icon: "🧩" |
| 33 | + title: "Standard control" |
| 34 | + desc: "Future represents execution, completion, and cancellation together." |
| 35 | +- icon: "🔗" |
| 36 | + title: "Composable" |
| 37 | + desc: "Interruption works with blocking queues, locks, executors, and virtual threads." |
| 38 | +support: |
| 39 | + state: "available" |
| 40 | + description: "Future and ExecutorService have been available since JDK 5 (Sept 2004)." |
| 41 | +prev: "concurrency/lock-free-lazy-init" |
| 42 | +next: "io/http-client" |
| 43 | +related: |
| 44 | +- "concurrency/executor-try-with-resources" |
| 45 | +- "concurrency/structured-concurrency" |
| 46 | +- "concurrency/virtual-threads" |
| 47 | +tags: |
| 48 | +- concurrency |
| 49 | +- async |
| 50 | +docs: |
| 51 | +- title: "Future" |
| 52 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/Future.html" |
| 53 | +- title: "Thread.stop() deprecation" |
| 54 | + href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Thread.html#stop()" |
0 commit comments