Skip to content

Commit 42a2be7

Browse files
Copilotbrunoborges
andauthored
Add thread-stop-to-cooperative-cancellation pattern
Co-authored-by: brunoborges <129743+brunoborges@users.noreply.github.com>
1 parent a64922d commit 42a2be7

19 files changed

Lines changed: 339 additions & 2 deletions

content/concurrency/lock-free-lazy-init.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ support:
5050
state: "preview"
5151
description: "Preview in JDK 25 (JEP 502, StableValue). Requires --enable-preview."
5252
prev: "concurrency/concurrent-http-virtual"
53-
next: "io/http-client"
53+
next: "concurrency/thread-stop-to-cooperative-cancellation"
5454
related:
5555
- "concurrency/virtual-threads"
5656
- "concurrency/structured-concurrency"
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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()"

content/io/http-client.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ whyModernWins:
4242
support:
4343
state: "available"
4444
description: "Widely available since JDK 11 (Sept 2018)"
45-
prev: "concurrency/lock-free-lazy-init"
45+
prev: "concurrency/thread-stop-to-cooperative-cancellation"
4646
next: "io/http-websocket-client"
4747
related:
4848
- "io/reading-files"
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
///usr/bin/env jbang "$0" "$@" ; exit $?
2+
//JAVA 25+
3+
import java.util.concurrent.*;
4+
5+
/// Proof: thread-stop-to-cooperative-cancellation
6+
/// Source: content/concurrency/thread-stop-to-cooperative-cancellation.yaml
7+
void main() throws Exception {
8+
Runnable runTask = () -> {
9+
try {
10+
while (!Thread.currentThread().isInterrupted()) {
11+
Thread.sleep(10);
12+
}
13+
} catch (InterruptedException e) {
14+
Thread.currentThread().interrupt();
15+
}
16+
};
17+
18+
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
19+
Future<?> worker = executor.submit(runTask);
20+
21+
// Requests interruption; the task must cooperate.
22+
worker.cancel(true);
23+
}
24+
}

social/queue.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,4 @@ tooling/stack-walker
126126
collections/map-compute-and-merge
127127
io/http-websocket-client
128128
security/security-manager-migration
129+
concurrency/thread-stop-to-cooperative-cancellation

social/tweets.yaml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1277,4 +1277,14 @@ security/security-manager-migration: |-
12771277
12781278
🔗 https://javaevolved.github.io/security/security-manager-migration.html
12791279
1280+
#Java #JavaEvolved
1281+
concurrency/thread-stop-to-cooperative-cancellation: |-
1282+
☕ Unsafe thread termination to cooperative cancellation
1283+
1284+
Replace Thread.stop() and ad hoc shared flags with interruption-a…
1285+
1286+
Thread.stop() → Future.cancel(true) (JDK 5+)
1287+
1288+
🔗 https://javaevolved.github.io/concurrency/thread-stop-to-cooperative-cancellation.html
1289+
12801290
#Java #JavaEvolved
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
title: "من الإنهاء غير الآمن للخيوط إلى الإلغاء التعاوني"
2+
oldApproach: "Thread.stop()"
3+
modernApproach: "Future.cancel(true)"
4+
summary: "استبدل Thread.stop() والأعلام المشتركة المؤقتة بإلغاء مهام واعٍ بالمقاطعة."
5+
explanation: "يمكن لـ Thread.stop() إنهاء الكود بينما يمتلك مراقبات (monitors) أو أثناء تحديث حالة مشتركة، مما يترك الكائنات تالفة. الإلغاء الحديث تعاوني: ألغِ الـ Future بالمقاطعة، وانشر InterruptedException حيثما أمكن، واستعد حالة المقاطعة عندما لا يمكن نشرها، وصمّم المهمة للوصول إلى نقاط إلغاء آمنة."
6+
whyModernWins:
7+
- icon: "🛡"
8+
title: "يحافظ على الثوابت"
9+
desc: "تتوقف المهام فقط عند مسارات الكود المصممة للإلغاء."
10+
- icon: "🧩"
11+
title: "تحكم موحّد"
12+
desc: "يمثّل Future التنفيذ والاكتمال والإلغاء معاً."
13+
- icon: "🔗"
14+
title: "قابل للتركيب"
15+
desc: "تعمل المقاطعة مع قوائم الانتظار المحظورة والأقفال والمنفذات والخيوط الافتراضية."
16+
support:
17+
description: "تتوفر Future وExecutorService منذ JDK 5 (سبتمبر 2004)."
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
title: অনিরাপদ থ্রেড টার্মিনেশন থেকে কোঅপারেটিভ ক্যান্সেলেশন
3+
oldApproach: Thread.stop()
4+
modernApproach: Future.cancel(true)
5+
summary: Thread.stop() এবং ad hoc শেয়ার্ড ফ্ল্যাগগুলোকে ইন্টারাপশন-অ্যাওয়ার টাস্ক ক্যান্সেলেশন দিয়ে প্রতিস্থাপন করুন।
6+
explanation: Thread.stop() মনিটর ধরে রাখা বা শেয়ার্ড স্টেট আপডেট করার সময় কোড টার্মিনেট করতে পারে, যার ফলে অবজেক্টগুলো ক্ষতিগ্রস্ত থেকে যেতে পারে। আধুনিক ক্যান্সেলেশন কোঅপারেটিভ ইন্টারাপশন দিয়ে Future ক্যান্সেল করুন, যেখানে সম্ভব InterruptedException প্রোপাগেট করুন, প্রোপাগেট করা সম্ভব না হলে ইন্টারাপ্ট স্ট্যাটাস পুনরুদ্ধার করুন, এবং টাস্কটিকে নিরাপদ ক্যান্সেলেশন পয়েন্টে পৌঁছানোর জন্য ডিজাইন করুন।
7+
whyModernWins:
8+
- icon: "🛡"
9+
title: ইনভ্যারিয়েন্ট সংরক্ষণ করে
10+
desc: টাস্কগুলো শুধুমাত্র ক্যান্সেলেশনের জন্য ডিজাইন করা কোড পাথে থামে।
11+
- icon: "🧩"
12+
title: স্ট্যান্ডার্ড কন্ট্রোল
13+
desc: Future এক্সিকিউশন, কমপ্লিশন এবং ক্যান্সেলেশন একসাথে উপস্থাপন করে।
14+
- icon: "🔗"
15+
title: কম্পোজেবল
16+
desc: ইন্টারাপশন ব্লকিং কিউ, লক, executor এবং ভার্চুয়াল থ্রেডের সাথে কাজ করে।
17+
support:
18+
description: Future এবং ExecutorService JDK 5 (সেপ্টেম্বর ২০০৪) থেকে উপলব্ধ।
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
title: Unsichere Thread-Beendigung zu kooperativer Abbruchsteuerung
2+
oldApproach: Thread.stop()
3+
modernApproach: Future.cancel(true)
4+
summary: Ersetzen Sie Thread.stop() und ad-hoc geteilte Flags durch unterbrechungsbewusste Aufgabenabbrüche.
5+
explanation: "Thread.stop() kann Code beenden, während er Monitore besitzt oder gemeinsam\
6+
\ genutzten Zustand aktualisiert, wodurch Objekte beschädigt bleiben können. Moderne\
7+
\ Abbruchsteuerung ist kooperativ: Brechen Sie das Future mit Unterbrechung ab,\
8+
\ leiten Sie InterruptedException weiter, wo möglich, stellen Sie den Unterbrechungsstatus\
9+
\ wieder her, wenn dies nicht möglich ist, und gestalten Sie die Aufgabe so, dass\
10+
\ sie sichere Abbruchpunkte erreicht."
11+
whyModernWins:
12+
- icon: "🛡"
13+
title: Bewahrt Invarianten
14+
desc: Aufgaben stoppen nur an Codepfaden, die für den Abbruch ausgelegt sind.
15+
- icon: "🧩"
16+
title: Einheitliche Steuerung
17+
desc: Future stellt Ausführung, Abschluss und Abbruch gemeinsam dar.
18+
- icon: "🔗"
19+
title: Komponierbar
20+
desc: Unterbrechung funktioniert mit Blocking-Queues, Locks, Executors und virtuellen Threads.
21+
support:
22+
description: "Future und ExecutorService sind seit JDK 5 (Sept. 2004) verfügbar."
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
title: Terminación insegura de hilos a cancelación cooperativa
2+
oldApproach: Thread.stop()
3+
modernApproach: Future.cancel(true)
4+
summary: Sustituye Thread.stop() y las banderas compartidas improvisadas por una cancelación
5+
de tareas consciente de la interrupción.
6+
explanation: Thread.stop() puede terminar el código mientras posee monitores o está actualizando
7+
estado compartido, dejando los objetos dañados. La cancelación moderna es cooperativa cancela
8+
el Future con interrupción, propaga InterruptedException cuando sea posible, restaura el
9+
estado de interrupción cuando no se puede propagar, y diseña la tarea para que alcance puntos
10+
seguros de cancelación.
11+
whyModernWins:
12+
- icon: 🛡
13+
title: Preserva invariantes
14+
desc: Las tareas se detienen solo en rutas de código diseñadas para la cancelación.
15+
- icon: 🧩
16+
title: Control estándar
17+
desc: Future representa la ejecución, la finalización y la cancelación en conjunto.
18+
- icon: 🔗
19+
title: Componible
20+
desc: La interrupción funciona con colas bloqueantes, locks, executors e hilos virtuales.
21+
support:
22+
description: Future y ExecutorService están disponibles desde JDK 5 (sept. 2004).

0 commit comments

Comments
 (0)