Design your own Threadpool
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-05-31
Problem Statement
Design and implement a custom Thread Pool that can manage a fixed number of worker threads to execute submitted tasks concurrently. The system should efficiently handle task execution, manage a queue of pending tasks, and ensure proper thread lifecycle management.
🔶 Functional Requirements
1.submit(Runnable task)
•Accepts a task (Runnable) and places it in the work queue.
•Tasks are picked up by idle worker threads.
2.Worker Thread Management
•The pool should create and maintain a fixed number of worker threads.
•Each worker thread continuously fetches tasks from the queue and executes them.
3.Shutdown
•shutdown(): Gracefully stop accepting new tasks but allow already submitted tasks to complete.
•shutdownNow(): Immediately attempt to stop all running tasks and clear the queue.
4.Queueing
•Maintain a blocking queue for pending tasks.
•If the queue is full, reject tasks (with a RejectedExecutionHandler or similar).
🔶 Non-Functional Requirements
•Concurrency Safety: Must handle multiple producers (submitters) and multiple consumers (worker threads) safely.
•Scalability: Should efficiently handle thousands of short-lived tasks.
•Performance: Ensure low latency in task assignment.
•Thread Lifecycle Management: Threads should be reusable instead of being created/destroyed frequently.
🔶 Constraints
•Thread pool size (number of worker threads) is fixed at initialization.
•The task queue can be bounded or unbounded depending on configuration.
•Tasks implement Runnable (or a similar functional interface).
•Thread safety must be guaranteed without deadlocks or race conditions.
🔶 Example Use Case
1
2ThreadPool pool = new ThreadPool(3, 10); // 3 worker threads, queue capacity = 10
3
4pool.submit(() -> System.out.println("Task 1 executed"));
5pool.submit(() -> System.out.println("Task 2 executed"));
6pool.submit(() -> System.out.println("Task 3 executed"));
7
8pool.shutdown();Expected Behavior:
•At most 3 tasks run in parallel.
•Extra tasks wait in the queue until a worker becomes free.
•On shutdown(), the pool stops after finishing pending tasks.
👉 In short:
Design a thread pool class that manages a fixed number of worker threads, supports task submission, executes tasks concurrently from a queue, and provides controlled shutdown, ensuring thread-safety and efficiency.