Implement ThreadPoolExecutor (Java, no API use)

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-03-16

Problem Statement

Implementing a ThreadPoolExecutor like system in Java without using the built-in concurrency API. The thread pool should manage a fixed number of threads and allow multiple tasks to be executed concurrently.


✅ Functional Requirements


1.Thread Pool Operations
•submit(Runnable task): Submit a new task to the pool.
•shutdown(): Gracefully stop accepting new tasks and finish all ongoing tasks.
•Optional: shutdownNow(): Immediately stop executing tasks and terminate threads.
2.Task Queue
•Maintain a thread-safe task queue (FIFO) for pending tasks.
•If all threads are busy, tasks wait in the queue.
3.Worker Threads
•A fixed number of threads (poolSize) should be created at initialization.
•Threads continuously fetch tasks from the queue and execute them.
4.Thread Safety & Concurrency
•Ensure thread-safe access to the task queue.
•Avoid race conditions, deadlocks, and task loss.
5.Optional Features
•Configurable corePoolSize and maxPoolSize.
•Support for task timeout or cancellation.
•Task prioritization.


🔐 Constraints & Assumptions


•Do not use Java’s built-in ThreadPoolExecutor or BlockingQueue.
•Tasks are of type Runnable.
•Focus is on LLD, concurrency, and worker-thread management.
•Single-machine implementation.


🧱 Key Components & Classes


1.TaskQueue Class
•Thread-safe queue for tasks using synchronized and wait/notify.
1 2class TaskQueue { 3 private LinkedList<Runnable> queue = new LinkedList<>(); 4 private int capacity; 5 6 public TaskQueue(int capacity) { this.capacity = capacity; } 7 8 public synchronized void enqueue(Runnable task) throws InterruptedException { 9 while (queue.size() == capacity) wait(); 10 queue.addLast(task); 11 notifyAll(); 12 } 13 14 public synchronized Runnable dequeue() throws InterruptedException { 15 while (queue.isEmpty()) wait(); 16 Runnable task = queue.removeFirst(); 17 notifyAll(); 18 return task; 19 } 20}
1.Worker Thread Class
1 2class Worker extends Thread { 3 private TaskQueue taskQueue; 4 private boolean isRunning = true; 5 6 public Worker(TaskQueue taskQueue) { this.taskQueue = taskQueue; } 7 8 public void run() { 9 while (isRunning) { 10 try { 11 Runnable task = taskQueue.dequeue(); 12 task.run(); 13 } catch (InterruptedException e) { 14 isRunning = false; 15 } 16 } 17 } 18 19 public void stopWorker() { isRunning = false; this.interrupt(); } 20}
1.ThreadPoolExecutor Class
1 2class ThreadPoolExecutor { 3 private TaskQueue taskQueue; 4 private List<Worker> workers; 5 6 public ThreadPoolExecutor(int poolSize, int queueCapacity) { 7 taskQueue = new TaskQueue(queueCapacity); 8 workers = new ArrayList<>(); 9 for (int i = 0; i < poolSize; i++) { 10 Worker worker = new Worker(taskQueue); 11 worker.start(); 12 workers.add(worker); 13 } 14 } 15 16 public void submit(Runnable task) throws InterruptedException { 17 taskQueue.enqueue(task); 18 } 19 20 public void shutdown() { 21 for (Worker worker : workers) { 22 worker.stopWorker(); 23 } 24 } 25}


🔄 Example Workflow


1.Initialize ThreadPoolExecutor with poolSize = 5 and queueCapacity = 10.
2.Submit multiple tasks via submit(task).
3.Worker threads fetch tasks from TaskQueue and execute them.
4.When shutdown() is called, threads finish current tasks and terminate.


🧪 Expected Deliverables


•Class diagram showing ThreadPoolExecutor, Worker, and TaskQueue.
•Implementation of submit, enqueue, dequeue, and shutdown with thread safety.
•Test cases:
•Submit multiple tasks concurrently
•Verify all tasks are executed
•Ensure no deadlocks or task loss
•Shutdown gracefully stops workers


💡 Discussion Points / Trade-offs


1.Blocking Strategy
•synchronized + wait/notify ensures safe blocking but may have contention under high concurrency.
2.Queue Choice
•LinkedList used for FIFO behavior; alternatives: circular buffer or custom heap for priority tasks.
3.Thread Management
•Fixed number of threads avoids excessive context switching.
•Optionally support dynamic scaling for more advanced implementations.
4.Extensibility
•Add features like task prioritization, timeouts, and rejection policies.


Solution

Comments