|
| 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" |
0 commit comments