Skip to content

Commit 57f7074

Browse files
authored
Merge pull request #211 from javaevolved/copilot/timer-task-to-scheduled-executor
Add pattern: Timer and TimerTask → ScheduledExecutorService
2 parents b4a5840 + 1741fcb commit 57f7074

19 files changed

Lines changed: 379 additions & 2 deletions

content/concurrency/thread-stop-to-cooperative-cancellation.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ support:
3939
state: "available"
4040
description: "Future and ExecutorService have been available since JDK 5 (Sept 2004)."
4141
prev: "concurrency/wait-notify-to-blocking-queue"
42-
next: "io/http-client"
42+
next: "concurrency/timer-task-to-scheduled-executor"
4343
related:
4444
- "concurrency/executor-try-with-resources"
4545
- "concurrency/structured-concurrency"
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
---
2+
id: 79baafd3-9ac2-4148-a6fb-db50c9cf5783
3+
slug: "timer-task-to-scheduled-executor"
4+
title: "Timer tasks to scheduled executors"
5+
category: "concurrency"
6+
difficulty: "intermediate"
7+
jdkVersion: "5"
8+
oldLabel: "Timer and TimerTask"
9+
modernLabel: "ScheduledExecutorService"
10+
oldApproach: "Timer and TimerTask"
11+
modernApproach: "ScheduledExecutorService"
12+
oldCode: |-
13+
Timer timer = new Timer("refresh-timer");
14+
timer.scheduleAtFixedRate(new TimerTask() {
15+
@Override
16+
public void run() {
17+
refresh();
18+
}
19+
}, 0, 60_000);
20+
modernCode: |-
21+
ScheduledExecutorService scheduler =
22+
Executors.newScheduledThreadPool(2);
23+
24+
scheduler.scheduleAtFixedRate(
25+
this::refresh, 0, 1, TimeUnit.MINUTES);
26+
summary: "Replace Timer and TimerTask with ScheduledExecutorService for robust scheduled work."
27+
explanation: "Timer executes every task on one thread, so one long-running task delays\
28+
\ the others, and an unchecked exception terminates the timer thread. ScheduledExecutorService\
29+
\ uses the executor framework, supports multiple workers, returns ScheduledFuture\
30+
\ handles, and provides explicit lifecycle management. The owning component must\
31+
\ shut the scheduler down when it is no longer needed."
32+
whyModernWins:
33+
- icon: "🧵"
34+
title: "Better isolation"
35+
desc: "A configurable thread pool prevents unrelated schedules from sharing one fragile worker."
36+
- icon: "🛡"
37+
title: "Robust execution"
38+
desc: "One failing task does not terminate the scheduler itself."
39+
- icon: "🎛"
40+
title: "Controllable lifecycle"
41+
desc: "Futures, cancellation, delays, and shutdown use standard executor APIs."
42+
support:
43+
state: "available"
44+
description: "Widely available since JDK 5 (Sept 2004)"
45+
prev: "concurrency/thread-stop-to-cooperative-cancellation"
46+
next: "io/http-client"
47+
related:
48+
- "concurrency/executor-try-with-resources"
49+
- "concurrency/thread-sleep-duration"
50+
- "concurrency/structured-concurrency"
51+
tags:
52+
- concurrency
53+
docs:
54+
- title: "ScheduledExecutorService"
55+
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/ScheduledExecutorService.html"
56+
- title: "Executors"
57+
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/Executors.html"

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/thread-stop-to-cooperative-cancellation"
45+
prev: "concurrency/timer-task-to-scheduled-executor"
4646
next: "io/http-websocket-client"
4747
related:
4848
- "io/reading-files"
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
///usr/bin/env jbang "$0" "$@" ; exit $?
2+
//JAVA 25+
3+
import java.util.concurrent.*;
4+
5+
/// Proof: timer-task-to-scheduled-executor
6+
/// Source: content/concurrency/timer-task-to-scheduled-executor.yaml
7+
void main() throws Exception {
8+
Runnable refresh = () -> System.out.println("refresh");
9+
10+
ScheduledExecutorService scheduler =
11+
Executors.newScheduledThreadPool(2);
12+
13+
ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(
14+
refresh, 0, 1, TimeUnit.MINUTES);
15+
16+
future.cancel(false);
17+
scheduler.shutdown();
18+
}

social/queue.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,4 @@ concurrency/thread-stop-to-cooperative-cancellation
132132
io/explicit-charset-file-io
133133
tooling/class-newinstance-to-constructor
134134
concurrency/wait-notify-to-blocking-queue
135+
concurrency/timer-task-to-scheduled-executor

social/tweets.yaml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1337,4 +1337,14 @@ concurrency/wait-notify-to-blocking-queue: |-
13371337
13381338
🔗 https://javaevolved.github.io/concurrency/wait-notify-to-blocking-queue.html
13391339
1340+
#Java #JavaEvolved
1341+
concurrency/timer-task-to-scheduled-executor: |-
1342+
☕ Timer tasks to scheduled executors
1343+
1344+
Replace Timer and TimerTask with ScheduledExecutorService for robust scheduled w…
1345+
1346+
Timer and TimerTask → ScheduledExecutorService (JDK 5+)
1347+
1348+
🔗 https://javaevolved.github.io/concurrency/timer-task-to-scheduled-executor.html
1349+
13401350
#Java #JavaEvolved
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
title: "من مهام Timer إلى المنفذات المجدولة"
2+
oldApproach: "Timer و TimerTask"
3+
modernApproach: "ScheduledExecutorService"
4+
summary: "استبدل Timer و TimerTask بـ ScheduledExecutorService للحصول على عمل مجدول\
5+
\ أكثر قوة."
6+
explanation: "ينفذ Timer كل مهمة على خيط واحد، لذا فإن مهمة طويلة الأمد تؤخر المهام\
7+
\ الأخرى، ويؤدي استثناء غير معالج إلى إنهاء خيط المؤقت. يستخدم ScheduledExecutorService\
8+
\ إطار عمل المنفذات، ويدعم عدة عمال، ويعيد مقابض ScheduledFuture، ويوفر إدارة صريحة\
9+
\ لدورة الحياة. يجب على المكوّن المالك إيقاف المجدول عند عدم الحاجة إليه."
10+
whyModernWins:
11+
- icon: "🧵"
12+
title: "عزل أفضل"
13+
desc: "يمنع تجمع الخيوط القابل للتهيئة الجداول غير المرتبطة من مشاركة عامل واحد\
14+
\ هش."
15+
- icon: "🛡"
16+
title: "تنفيذ قوي"
17+
desc: "فشل مهمة واحدة لا ينهي المجدول نفسه."
18+
- icon: "🎛"
19+
title: "دورة حياة قابلة للتحكم"
20+
desc: "تستخدم الـ Futures والإلغاء والتأخيرات والإيقاف واجهات برمجة تطبيقات المنفذ\
21+
\ القياسية."
22+
support:
23+
description: "متوفر على نطاق واسع منذ JDK 5 (سبتمبر 2004)"
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
title: টাইমার টাস্ক থেকে শিডিউলড এক্সিকিউটরে
2+
oldApproach: Timer ও TimerTask
3+
modernApproach: ScheduledExecutorService
4+
summary: শক্তিশালী শিডিউল করা কাজের জন্য Timer ও TimerTask-কে ScheduledExecutorService
5+
দিয়ে প্রতিস্থাপন করুন।
6+
explanation: Timer প্রতিটি টাস্ক একটি মাত্র থ্রেডে চালায়, তাই একটি দীর্ঘসময় ধরে চলা
7+
টাস্ক অন্যগুলোকে বিলম্বিত করে, এবং একটি অনিয়ন্ত্রিত ব্যতিক্রম টাইমার থ্রেডকে বন্ধ
8+
করে দেয়। ScheduledExecutorService এক্সিকিউটর ফ্রেমওয়ার্ক ব্যবহার করে, একাধিক ওয়ার্কার
9+
সমর্থন করে, ScheduledFuture হ্যান্ডেল ফেরত দেয়, এবং স্পষ্ট লাইফসাইকেল ব্যবস্থাপনা
10+
প্রদান করে। মালিক কম্পোনেন্টকে আর প্রয়োজন না হলে শিডিউলার বন্ধ করে দিতে হবে।
11+
whyModernWins:
12+
- icon: 🧵
13+
title: উন্নত বিচ্ছিন্নতা
14+
desc: কনফিগারযোগ্য থ্রেড পুল অসম্পর্কিত শিডিউলগুলোকে একটি ভঙ্গুর ওয়ার্কার ভাগ করা থেকে
15+
বিরত রাখে।
16+
- icon: 🛡
17+
title: মজবুত এক্সিকিউশন
18+
desc: একটি ব্যর্থ টাস্ক শিডিউলারকে নিজেই বন্ধ করে দেয় না।
19+
- icon: 🎛
20+
title: নিয়ন্ত্রণযোগ্য লাইফসাইকেল
21+
desc: Future, বাতিলকরণ, বিলম্ব এবং বন্ধ করা স্ট্যান্ডার্ড এক্সিকিউটর API ব্যবহার করে।
22+
support:
23+
description: JDK 5 (সেপ্টেম্বর ২০০৪) থেকে ব্যাপকভাবে উপলব্ধ
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
title: Timer-Aufgaben zu geplanten Executors
2+
oldApproach: Timer und TimerTask
3+
modernApproach: ScheduledExecutorService
4+
summary: Ersetzen Sie Timer und TimerTask durch ScheduledExecutorService für robuste
5+
geplante Aufgaben.
6+
explanation: Timer führt jede Aufgabe auf einem Thread aus, sodass eine lang laufende
7+
Aufgabe die anderen verzögert und eine unbehandelte Ausnahme den Timer-Thread beendet.
8+
ScheduledExecutorService nutzt das Executor-Framework, unterstützt mehrere Worker,
9+
liefert ScheduledFuture-Handles und bietet ein explizites Lifecycle-Management.
10+
Die besitzende Komponente muss den Scheduler herunterfahren, wenn er nicht mehr
11+
benötigt wird.
12+
whyModernWins:
13+
- icon: 🧵
14+
title: Bessere Isolation
15+
desc: Ein konfigurierbarer Thread-Pool verhindert, dass sich unabhängige Zeitpläne
16+
einen fragilen Worker teilen.
17+
- icon: 🛡
18+
title: Robuste Ausführung
19+
desc: Eine fehlschlagende Aufgabe beendet nicht den Scheduler selbst.
20+
- icon: 🎛
21+
title: Steuerbarer Lebenszyklus
22+
desc: 'Futures, Abbruch, Verzögerungen und Herunterfahren nutzen Standard-Executor-APIs.'
23+
support:
24+
description: Weithin verfügbar seit JDK 5 (Sept. 2004)
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
title: De tareas de Timer a ejecutores programados
2+
oldApproach: Timer y TimerTask
3+
modernApproach: ScheduledExecutorService
4+
summary: Reemplaza Timer y TimerTask por ScheduledExecutorService para un trabajo
5+
programado robusto.
6+
explanation: Timer ejecuta cada tarea en un solo hilo, por lo que una tarea de larga
7+
duración retrasa a las demás, y una excepción no controlada termina el hilo del
8+
timer. ScheduledExecutorService usa el framework de executors, admite múltiples
9+
workers, devuelve manejadores ScheduledFuture y ofrece una gestión explícita del
10+
ciclo de vida. El componente propietario debe apagar el scheduler cuando ya no
11+
se necesite.
12+
whyModernWins:
13+
- icon: 🧵
14+
title: Mejor aislamiento
15+
desc: Un pool de hilos configurable evita que tareas no relacionadas compartan
16+
un único worker frágil.
17+
- icon: 🛡
18+
title: Ejecución robusta
19+
desc: Una tarea que falla no termina el propio scheduler.
20+
- icon: 🎛
21+
title: Ciclo de vida controlable
22+
desc: 'Futures, cancelación, retrasos y apagado usan las API estándar de executors.'
23+
support:
24+
description: Ampliamente disponible desde JDK 5 (sept. 2004)

0 commit comments

Comments
 (0)