Design a Thread Pool Executor
HardConcurrencyThread PoolBlockingQueueExecutorServiceWorker ThreadsTask Queue
Problem Statement
Implement a simplified ThreadPoolExecutor from scratch. Your pool maintains a fixed number of worker threads that pull tasks from a shared work queue and execute them. Implement the following interface:
class MyThreadPool {
public MyThreadPool(int corePoolSize, int maxPoolSize, int queueCapacity) {}
public void submit(Runnable task) throws RejectedExecutionException {}
public void shutdown() {}
public void awaitTermination() throws InterruptedException {}
public boolean isShutdown() {}
public int getActiveCount() {}
public int getQueueSize() {}
}
Key Entities
- Worker Thread: Long-lived thread that loops, pulling tasks from the queue.
- Task Queue: Bounded
BlockingQueue<Runnable>storing submitted tasks. - Core Pool: Minimum number of always-alive threads.
- Max Pool: Upper limit; extra threads spawned when queue is full.
- Rejection Policy: Throw
RejectedExecutionExceptionwhen maxPool is reached and queue is full.
Requirements
- Maintain
corePoolSizethreads always running (even when idle). - Spawn additional threads up to
maxPoolSizewhen the queue fills. shutdown()stops accepting new tasks;awaitTermination()blocks until all queued tasks complete.- Support graceful draining — workers finish in-progress tasks before stopping.
- Thread-safe
submit(),shutdown(), and status methods.
Asked at: Google, Amazon, Microsoft, Uber, Netflix, LinkedIn, Flipkart
!Constraints
- 1 ≤ corePoolSize ≤ maxPoolSize ≤ 100
- 1 ≤ queueCapacity ≤ 10000
- Tasks submitted after shutdown() must be rejected.
- awaitTermination() must block the calling thread until all tasks complete.
- Workers must not busy-wait — they block on the queue.
Output
Run or submit your code to see output here.