Scheduled Executer Service
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2021-03-24
Problem Statement
Design and implement a Scheduled Executor Service that allows scheduling and execution of tasks after a given delay or at fixed intervals. The service should support the following operations:
1.<span></span>schedule(task, delay): Schedule a task to run once after the given delay.
2.<span></span>scheduleAtFixedRate(task, initialDelay, period): Schedule a task to run periodically, starting after the initial delay, and then repeatedly at a fixed rate (time between successive task starts is constant).
3.<span></span>scheduleWithFixedDelay(task, initialDelay, delay): Schedule a task to run periodically, where the delay is measured between the completion of one execution and the start of the next.
4.<span></span>shutdown(): Gracefully stop accepting new tasks and allow already scheduled tasks to complete.
The implementation should be thread-safe and capable of handling multiple scheduled tasks concurrently. Internally, it should manage worker threads (using a pool or dedicated threads) and maintain a scheduling mechanism (such as a priority queue or min-heap based on execution time) to ensure tasks are executed at the correct time.
The system should ensure:
1.<span></span>Accurate and timely execution of tasks.
2.<span></span>No race conditions or inconsistent states in concurrent environments.
3.<span></span>Efficient resource utilization by reusing worker threads.