Why use a thread pool?
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A thread pool is a small, fixed team of worker threads that runs many tasks one after another, instead of creating a new thread for every task. Java gives you ready-made pools through the Executors class.
The cost of creating a thread for every task
A thread pool keeps a fixed set of worker threads and gives them tasks from a queue, so threads are reused instead of being created for every task.
A platform thread is the normal Java thread you create with new Thread(...). Each one is backed by a thread of the operating system, so creating it is not free.
Example 1 · One new thread for every order
import java.util.HashSet;import java.util.Set;
class PackingDesk { private final Set<String> workers = new HashSet<>(); private int ordersPacked = 0;
synchronized void pack(int orderNo) { workers.add(Thread.currentThread().getName()); // who packed it ordersPacked++; }
synchronized String report() { return "Orders packed: " + ordersPacked + ", threads used: " + workers.size(); }}
public class ThreadPerOrderDemo { public static void main(String[] args) throws InterruptedException { PackingDesk desk = new PackingDesk(); int orders = 1000; Thread[] threads = new Thread[orders];
for (int i = 0; i < orders; i++) { int orderNo = i + 1; threads[i] = new Thread(() -> desk.pack(orderNo), "order-" + orderNo); threads[i].start(); } for (Thread t : threads) { t.join(); // wait for every order } System.out.println(desk.report()); }}Orders packed: 1000, threads used: 1000
What this code does
PackingDeskrecords the name of the thread that packs each order. Its methods aresynchronizedbecause many threads call them at the same time.- Each order is tiny, yet the program creates, starts and destroys 1000 threads to pack 1000 orders. Starting a thread costs far more than the work each one does here.
The system must reserve stack memory for it, register it with its scheduler, and clean all of that up when the thread ends.
For a few threads this cost does not matter. But a server that starts a new thread for every request, such as every Tatkal booking at 10 AM, may create thousands of threads in a few seconds. Memory runs low, and the CPU spends more time switching between threads than doing real work. There is also no upper limit. If 50,000 requests arrive at once, the program tries to create 50,000 threads. On many machines it then fails with an OutOfMemoryError saying it is unable to create a native thread.
-Xss setting.A thread pool: fixed staff and a queue of orders
A thread pool keeps a fixed number of worker threads alive and gives them tasks from a queue, a waiting line where the first task in is the first task out.
Example 2 · The same 1000 orders on a pool of 3 packers
import java.util.HashSet;import java.util.Set;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
class PackingDesk { private final Set<String> workers = new HashSet<>(); private int ordersPacked = 0;
synchronized void pack(int orderNo) { workers.add(Thread.currentThread().getName()); // who packed it ordersPacked++; }
synchronized String report() { return "Orders packed: " + ordersPacked + ", threads used: " + workers.size(); }}
public class PoolPackingDemo { public static void main(String[] args) throws InterruptedException { PackingDesk desk = new PackingDesk(); ExecutorService packers = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 1000; i++) { int orderNo = i; packers.submit(() -> desk.pack(orderNo)); // join the queue }
packers.shutdown(); // no more orders today packers.awaitTermination(5, TimeUnit.SECONDS); System.out.println(desk.report()); }}Orders packed: 1000, threads used: 3
What this code does
- All 1000 orders are packed, but only 3 threads were ever created. Each packer took the next order from the queue as soon as it finished one.
- The main thread only places orders with
submitand does not pack anything.shutdownplusawaitTerminationmake it wait until the queue is empty before it prints the report.
Think of the packing desk of an online store with three packers. Orders wait in a line, and each free packer takes the next order. The store does not hire a new packer for every order and send them home after one parcel. The same three packers work all day. A pool works the same way: its threads are created once and reused for many tasks.
This gives two benefits. The cost of creating threads is paid only a few times. And the number of threads has a limit, so a sudden rush makes the queue longer instead of crashing the program.
Task versus thread
A task is a piece of work for a pool to run, usually a Runnable or a lambda. A thread is the worker that runs tasks; a pool decides which of its threads runs which task.
A task is a piece of work: "pack order 17" or "email the result to roll number 42". In Java a task is usually a Runnable, an object with one run() method, often written as a lambda. A thread is the worker that runs tasks.
Example 3 · Four tasks, one thread
import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class TaskVersusThreadDemo { static void say(String work) { System.out.println(work + " on " + Thread.currentThread().getName()); }
public static void main(String[] args) throws InterruptedException { List<Runnable> tasks = List.of( () -> say("Print hall ticket"), () -> say("Send fee receipt "), () -> say("Mark attendance "), () -> say("Email timetable "));
ExecutorService pool = Executors.newFixedThreadPool(1); for (Runnable task : tasks) { pool.submit(task); } pool.shutdown(); pool.awaitTermination(5, TimeUnit.SECONDS); System.out.println("Tasks: " + tasks.size() + ", threads in the pool: 1"); }}Print hall ticket on pool-1-thread-1 Send fee receipt on pool-1-thread-1 Mark attendance on pool-1-thread-1 Email timetable on pool-1-thread-1 Tasks: 4, threads in the pool: 1
What this code does
- The four lambdas are tasks: plain
Runnableobjects in a list. Creating them starts nothing; they are just descriptions of work. - A pool with one thread runs the tasks one by one, in the order they were submitted, all on the same thread
pool-1-thread-1.
When you create threads by hand, the two are glued together: one new Thread(task) runs exactly one task and then ends. A pool separates them. You hand over tasks, and the pool decides which of its threads runs each task and when. So with a pool you stop asking "how many threads should I start?" and ask "what work do I have?". The number of threads is set once, in one place.
Trace the code
Follow three tasks through a one-thread pool
Variables
None yet.
Output
(nothing printed yet)Line 5The pool starts with one worker thread and an empty queue.
Executors.newFixedThreadPool
Executors.newFixedThreadPool(n) creates a pool with n worker threads and a queue with no size limit. It returns an ExecutorService, the interface you use to give tasks to the pool and to stop it.
ExecutorService pool = Executors.newFixedThreadPool(4); // 4 worker threadspool.submit(() -> sendEmail(1)); // hand over a taskpool.submit(() -> sendEmail(2)); // returns at oncepool.shutdown(); // no new taskspool.awaitTermination(10, TimeUnit.SECONDS); // wait for the queued onesThree calls cover most programs. submit(task) puts the task in the queue and returns at once, without waiting for the task to run. shutdown() tells the pool that no more tasks are coming; tasks already in the queue still run. awaitTermination(time, unit) makes the calling thread wait until all those tasks have finished, or until the time runs out.
Example 4 · Exam result emails on a pool of 4
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class ResultEmailDemo { static void sendResult(int roll) { try { Thread.sleep(50); // pretend the mail server takes 50 ms } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } System.out.println(Thread.currentThread().getName() + " sent result to roll " + roll); }
public static void main(String[] args) throws InterruptedException { long start = System.currentTimeMillis(); ExecutorService mailers = Executors.newFixedThreadPool(4);
for (int roll = 1; roll <= 12; roll++) { int r = roll; mailers.submit(() -> sendResult(r)); }
mailers.shutdown(); mailers.awaitTermination(10, TimeUnit.SECONDS); long took = System.currentTimeMillis() - start; System.out.println("12 emails sent in about " + took + " ms"); }}pool-1-thread-1 sent result to roll 1 pool-1-thread-2 sent result to roll 2 pool-1-thread-2 sent result to roll 6 pool-1-thread-1 sent result to roll 5 pool-1-thread-3 sent result to roll 3 pool-1-thread-4 sent result to roll 4 pool-1-thread-2 sent result to roll 7 pool-1-thread-1 sent result to roll 8 pool-1-thread-3 sent result to roll 9 pool-1-thread-4 sent result to roll 10 pool-1-thread-1 sent result to roll 12 pool-1-thread-2 sent result to roll 11 12 emails sent in about 281 ms
What this code does
- Four mailer threads share 12 emails: each email takes 50 ms, so the batch needs about 3 rounds of 50 ms plus some start-up time, instead of 12 rounds (600 ms or more) on one thread. The order of the lines, the thread names and the time change from run to run.
- Only the names
pool-1-thread-1topool-1-thread-4appear: the pool never creates a fifth thread, however many emails are waiting.
Always shut a pool down. Its threads stay alive waiting for more work, so a program that never calls shutdown() keeps running after main ends. The lesson "Shut down a pool correctly" covers this in detail.
Order of execution
Run a batch of tasks on a pool
Put the steps in the order the program runs them.
pool-1-thread-1, pool-1-thread-2 and so on. The first number counts the pools created in this program, the second counts threads inside that pool.Next step
Check your understanding
12 quick questions