Java Concurrency Program · CD19
Build a Simple Thread Pool in Java
Creating a thread per task is expensive. A pool starts a few threads once, and each one keeps taking the next task from a shared queue.
Problem Statement
Write a pool with a fixed number of workers, submit(task) and shutdownAndWait(). Submitted tasks wait in a queue until a worker is free.
Shutdown runs every task already submitted, then stops the workers. Submitting after shutdown must fail.
Input/Output Examples
3 workers, 6 tasksOutput6 tasks on 3 threadsExplanation: each worker runs about two tasks.task n stores n × nOutput[1, 4, 9, 16, 25, 36]Explanation: every task ran exactly once.submit()OutputIllegalStateExceptionExplanation: the pool no longer accepts work.Visual Explanation
- StartworkersW1W2W3each waits on take()
- submit × 6queue123456workers take 1, 2, 3
- Reusequeue456a free worker takes the next task
- ShutdownqueueSTOPSTOPSTOPone poison pill per worker
- Done6 tasks, 3 threads
Because the stop markers go to the back of the queue, every task submitted before shutdown still runs.
Approaches
Both approaches create three workers and print the same checks. The first builds on BlockingQueue; the second does the waiting by hand.
Approach 1: BlockingQueue and Poison Pill (Recommended)
Idea: workers loop on tasks.take(); shutdown adds one special STOP task per worker and joins them.
- Start
nnamed worker threads. - Each worker takes a task, runs it and catches its exceptions.
- On shutdown, set a flag and add one STOP marker per worker.
- Join every worker.
Time: O(1) · Space: O(q). per submit; q is the number of queued tasks.
Approach 2: Deque With wait() and notify()
Idea: guard an ArrayDeque with the pool's monitor; workers wait while it is empty, submit() notifies one of them.
- Workers wait while the deque is empty and the pool is running.
- They take a task inside the lock and run it outside the lock.
- Shutdown sets the flag and calls
notifyAll(); workers exit once the deque is empty.
Time: O(1) · Space: O(q).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Thread timing changes from run to run, so the programs print checks (true or false) instead of raw timings; both tabs print the same output.
Approach 1: BlockingQueue and Poison Pill (Recommended)
The queue handles all waiting and waking, so the pool itself has almost no locking.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ThreadPoolBlockingQueue {
// Workers loop forever taking tasks from a shared queue; a "poison pill" task tells each one to stop
static class SimplePool {
private static final Runnable STOP = () -> { };
private final BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<>();
private final List<Thread> workers = new ArrayList<>();
private volatile boolean shutdown;
SimplePool(int size) {
for (int i = 1; i <= size; i++) {
Thread t = new Thread(this::runWorker, "pool-worker-" + i);
workers.add(t);
t.start();
}
}
private void runWorker() {
try {
while (true) {
Runnable task = tasks.take(); // waits while the queue is empty
if (task == STOP) return;
try {
task.run();
} catch (RuntimeException e) {
System.out.println("task failed: " + e); // a bad task must not kill the worker
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
synchronized void submit(Runnable task) {
if (shutdown) throw new IllegalStateException("pool is shut down");
tasks.add(task);
}
void shutdownAndWait() throws InterruptedException {
synchronized (this) {
shutdown = true;
for (int i = 0; i < workers.size(); i++) tasks.add(STOP); // queued after the real tasks
}
for (Thread t : workers) t.join();
}
int workerCount() { return workers.size(); }
}
public static void main(String[] args) throws InterruptedException {
SimplePool pool = new SimplePool(3);
int[] squares = new int[6];
Set<String> threadNames = ConcurrentHashMap.newKeySet();
for (int i = 0; i < 6; i++) {
final int n = i + 1;
pool.submit(() -> {
threadNames.add(Thread.currentThread().getName());
sleep(100); // some work
squares[n - 1] = n * n;
});
}
pool.shutdownAndWait();
System.out.println("results: " + Arrays.toString(squares));
System.out.println("worker threads created: " + pool.workerCount());
System.out.println("every task ran on a pool thread: " + threadNames.stream().allMatch(s -> s.startsWith("pool-worker-")));
System.out.println("at most 3 threads used: " + (threadNames.size() <= 3));
try {
pool.submit(() -> { });
} catch (IllegalStateException e) {
System.out.println("submit after shutdown: " + e.getMessage());
}
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
results: [1, 4, 9, 16, 25, 36] worker threads created: 3 every task ran on a pool thread: true at most 3 threads used: true submit after shutdown: pool is shut down
Time complexity: O(1) · Space complexity: O(q).
Approach 2: Deque With wait() and notify()
Shows the mechanics a BlockingQueue hides.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.ArrayDeque;
import java.util.Deque;
public class ThreadPoolWaitNotify {
// The same pool with a plain deque guarded by the pool's monitor
static class SimplePool {
private final Deque<Runnable> tasks = new ArrayDeque<>();
private final List<Thread> workers = new ArrayList<>();
private boolean shutdown;
SimplePool(int size) {
for (int i = 1; i <= size; i++) {
Thread t = new Thread(this::runWorker, "pool-worker-" + i);
workers.add(t);
t.start();
}
}
private void runWorker() {
while (true) {
Runnable task;
synchronized (this) {
while (tasks.isEmpty() && !shutdown) {
try {
wait();
} catch (InterruptedException e) {
return;
}
}
if (tasks.isEmpty()) return; // shut down and nothing left to do
task = tasks.removeFirst();
}
try {
task.run(); // run outside the lock
} catch (RuntimeException e) {
System.out.println("task failed: " + e);
}
}
}
synchronized void submit(Runnable task) {
if (shutdown) throw new IllegalStateException("pool is shut down");
tasks.addLast(task);
notify(); // one new task needs one worker
}
void shutdownAndWait() throws InterruptedException {
synchronized (this) {
shutdown = true;
notifyAll();
}
for (Thread t : workers) t.join();
}
int workerCount() { return workers.size(); }
}
public static void main(String[] args) throws InterruptedException {
SimplePool pool = new SimplePool(3);
int[] squares = new int[6];
Set<String> threadNames = ConcurrentHashMap.newKeySet();
for (int i = 0; i < 6; i++) {
final int n = i + 1;
pool.submit(() -> {
threadNames.add(Thread.currentThread().getName());
sleep(100); // some work
squares[n - 1] = n * n;
});
}
pool.shutdownAndWait();
System.out.println("results: " + Arrays.toString(squares));
System.out.println("worker threads created: " + pool.workerCount());
System.out.println("every task ran on a pool thread: " + threadNames.stream().allMatch(s -> s.startsWith("pool-worker-")));
System.out.println("at most 3 threads used: " + (threadNames.size() <= 3));
try {
pool.submit(() -> { });
} catch (IllegalStateException e) {
System.out.println("submit after shutdown: " + e.getMessage());
}
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
results: [1, 4, 9, 16, 25, 36] worker threads created: 3 every task ran on a pool thread: true at most 3 threads used: true submit after shutdown: pool is shut down
Time complexity: O(1) · Space complexity: O(q).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| BlockingQueue and Poison Pill | O(1) | O(q) |
| Deque With wait() and notify() | O(1) | O(q) |
Submitting is a constant-time queue operation. Only three threads ever exist, no matter how many tasks are submitted.
Interview Tips and Recommended Approach
- Catch task exceptions inside the worker loop, or one bad task kills a worker for good.
- Run tasks outside any lock; otherwise only one task runs at a time.
- Explain poison pills as a clean way to stop consumers without interrupting them mid-task.
- In real code, use
Executors.newFixedThreadPool()or aThreadPoolExecutorwith a bounded queue.
Recommended Approach: BlockingQueue and Poison Pill
Why: it leaves the hard part, waiting and waking, to a well-tested BlockingQueue, so the pool code is short and easy to get right.