Implement schedule() method of ScheduledExecutorService in Java

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-05-19

Problem Statement

Designing a custom ScheduledExecutorService in Java that supports scheduling tasks to run after a fixed delay. The focus is on concurrency, thread safety, delayed execution, and modular design.


✅ Functional Requirements


1.Task Scheduling
•schedule(Runnable task, long delay, TimeUnit unit) schedules a one-time task to execute after the specified delay.
•Tasks should execute as close as possible to the scheduled time.
•Support concurrent scheduling from multiple threads.
2.Task Execution
•Tasks are executed by worker threads managed by the executor.
•Multiple tasks scheduled for the same time can execute concurrently.
3.Task Management
•Cancel a scheduled task before execution.
•Query the status of a scheduled task (pending, running, completed, canceled).
4.Concurrency & Thread Safety
•Handle thread-safe addition and removal of tasks.
•Ensure proper synchronization to avoid race conditions.
5.Optional Features
•Support recurring tasks (scheduleAtFixedRate, scheduleWithFixedDelay).
•Task prioritization if multiple tasks are scheduled for the same time.


🔐 Constraints & Assumptions


•Focus on LLD, class design, and concurrency, not on distributed execution.
•Tasks are small Runnable objects.
•Assume system clock is reliable.
•Implementing full ScheduledExecutorService API is optional; focus is on schedule().


🧱 Key Components & Classes


1.ScheduledTask Class
1 2public class ScheduledTask implements Comparable<ScheduledTask> { 3 private Runnable task; 4 private long executionTime; // absolute time in milliseconds 5 private String status; // PENDING, RUNNING, COMPLETED, CANCELED 6 7 public ScheduledTask(Runnable task, long executionTime) { 8 this.task = task; 9 this.executi executionTime; 10 this.status = "PENDING"; 11 } 12 13 public void execute() { 14 status = "RUNNING"; 15 task.run(); 16 status = "COMPLETED"; 17 } 18 19 @Override 20 public int compareTo(ScheduledTask other) { 21 return Long.compare(this.executionTime, other.executionTime); 22 } 23}
1.ScheduledExecutorServiceImpl Class
1 2public class ScheduledExecutorServiceImpl { 3 private PriorityBlockingQueue<ScheduledTask> taskQueue = new PriorityBlockingQueue<>(); 4 private ExecutorService workerPool = Executors.newFixedThreadPool(5); 5 private boolean running = true; 6 7 public void schedule(Runnable task, long delay, TimeUnit unit) { 8 long executi System.currentTimeMillis() + unit.toMillis(delay); 9 ScheduledTask scheduledTask = new ScheduledTask(task, executionTime); 10 taskQueue.add(scheduledTask); 11 } 12 13 public void start() { 14 Thread schedulerThread = new Thread(() -> { 15 while (running) { 16 try { 17 ScheduledTask nextTask = taskQueue.peek(); 18 if (nextTask != null) { 19 long waitTime = nextTask.getExecutionTime() - System.currentTimeMillis(); 20 if (waitTime <= 0) { 21 taskQueue.poll(); 22 workerPool.submit(nextTask::execute); 23 } else { 24 Thread.sleep(waitTime); 25 } 26 } 27 } catch (InterruptedException e) { 28 Thread.currentThread().interrupt(); 29 } 30 } 31 }); 32 schedulerThread.start(); 33 } 34 35 public void stop() { 36 running = false; 37 workerPool.shutdown(); 38 } 39}


🔄 Example Workflow


1.User calls schedule(() -> System.out.println("Task 1"), 5, TimeUnit.SECONDS) → adds ScheduledTask to the queue.
2.Scheduler thread checks the priority queue for the next task to execute.
3.When execution time arrives, task is polled from the queue and submitted to worker pool.
4.Task executes, updates status to COMPLETED.


🧪 Expected Deliverables


•Class diagram showing ScheduledTask and ScheduledExecutorServiceImpl.
•Implementation of schedule(), task queue management, and thread-safe execution.
•Test cases:
•Schedule multiple tasks with different delays
•Ensure tasks execute at correct times
•Cancel a task before execution
•Verify concurrent execution of multiple tasks


💡 Discussion Points


•Concurrency: thread-safe priority queue and worker pool.
•Timing Accuracy: handling delays due to thread wake-up latency.
•Extensibility: support recurring tasks and task prioritization.
•Performance: efficient scheduling and minimal blocking.


Solution

Comments