Skip to content

Commit 0a03462

Browse files
committed
feat: add ScheduledExecutorService demo with fixed-rate and delayed shutdown
WHAT was added: - Example program using ScheduledExecutorService to demonstrate periodic and delayed task execution. - Scheduled a repeating task with scheduleAtFixedRate() that prints a message every 5 seconds after initial delay. - Scheduled a one-time shutdown task with schedule() that triggers graceful shutdown after 20 seconds. - Code comments explaining differences between: - schedule() → run once after a delay - scheduleAtFixedRate() → run at a fixed rate regardless of task duration - scheduleWithFixedDelay() → run with a fixed delay after previous task completion WHY this matters: - Shows practical usage of ScheduledExecutorService for tasks like cron jobs, background health checks, or periodic monitoring. - Demonstrates scheduling patterns (fixed rate vs fixed delay) and highlights their semantic differences. - Includes proper shutdown scheduling to stop executor service gracefully after demonstration period. HOW it works: 1. Create ScheduledExecutorService with a single-thread pool. 2. Call scheduleAtFixedRate() with: - initial delay = 5s - period = 5s - TimeUnit.SECONDS This runs the task periodically at a fixed rate. 3. Call schedule() with a 20s delay to run a shutdown task that calls scheduler.shutdown(). 4. After shutdown, no new tasks are scheduled, and the executor terminates once running tasks finish. NOTES and GOTCHAS: - Fixed-rate tasks try to maintain exact start times. If execution takes longer than period, tasks may "pile up". - Fixed-delay tasks always wait the specified delay after completion, preventing pileup. - Always shut down executors explicitly to release resources; in production, use awaitTermination() for clean shutdown. - Be mindful of long-running tasks in scheduleAtFixedRate(), as they can cause thread starvation or memory pressure. - Use multiple threads in pool if tasks are long-running or blocking. PERF considerations: - For CPU-bound periodic tasks, keep thread pool close to CPU core count. - For IO-bound periodic tasks (like logging, polling, or health checks), a larger pool may be needed to overlap waits. - Excessively frequent scheduling (e.g., sub-second intervals) may cause high scheduling overhead. KEYWORDS: scheduledexecutorservice fixedrate fixeddelay periodic-tasks graceful-shutdown. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent cbc7650 commit 0a03462

File tree

1 file changed

+33
-0
lines changed
  • Section19MultiThreading/ThreadPooling/ExecutorsFramework/ScheduledExecutorsServices/src

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import java.util.concurrent.Executors;
2+
import java.util.concurrent.ScheduledExecutorService;
3+
import java.util.concurrent.ScheduledFuture;
4+
import java.util.concurrent.TimeUnit;
5+
6+
// ScheduledExecutorService ka use tab hota hai jab apko koi task
7+
// periodically (repeat interval par) ya ek specific delay ke baad run karna ho.
8+
9+
public class Main {
10+
public static void main(String[] args) {
11+
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
12+
13+
// Different scheduling methods available:
14+
// scheduler.schedule(...) -> ek specific delay ke baad run
15+
// scheduler.scheduleAtFixedRate(...) -> fix interval ke saath run (start times fixed)
16+
// scheduler.scheduleWithFixedDelay() -> ek task ke end ke baad delay dekar next run
17+
18+
// Example: Task har 5 seconds ke fixed rate par execute hoga.
19+
scheduler.scheduleAtFixedRate(() ->
20+
System.out.println("Task executed after Every 5 seconds delay !"),
21+
5,
22+
5,
23+
TimeUnit.SECONDS);
24+
25+
scheduler.schedule( () ->
26+
{
27+
System.out.println("Initiating shutdown...");
28+
scheduler.shutdown();
29+
}, 20, TimeUnit.SECONDS);
30+
31+
//scheduler.shutdown();
32+
}
33+
}

0 commit comments

Comments
 (0)