Java ExecutorService and Thread Pools
Six orders on six new threads works, but a thousand orders would mean a thousand threads. A fixed pool of three workers packs the same six in two seconds, shutdown closes the entrance while awaitTermination waits, and pools of 1, 3 and 6 take 6, 2 and 1 seconds.
What you will learn
- Explain the cost of starting a new thread for every task
- Run tasks on a fixed pool with newFixedThreadPool, submit and close
- Close a pool with shutdown and wait with awaitTermination
- See how pool size changes the total time
Before you start
- Creating threads in Java: Thread, Runnable and lambdas
- Java lambdas and functional interfaces
Instead of starting a new thread for every small task, keep a few workers and a queue of orders. The workers pick up the next order when they're free. That's a thread pool. Thread names and the order of lines below are from one run; yours may differ.
Six orders, six new threads
package org.studyeasy.s06l06;
public class Ex01_ThreadPerOrder {
static void pack(int order) {
String worker = Thread.currentThread().getName();
System.out.println(worker + " packs order " + order);
// packing takes 1 second
try { Thread.sleep(1000); } catch (InterruptedException e) { }
}
public static void main(String[] args) {
int created = 0;
for (int order = 1; order <= 6; order++) {
int n = order; // a lambda needs a fixed copy
new Thread(() -> pack(n)).start(); // a NEW thread each
created++;
}
System.out.println("Threads created: " + created);
}
}
Threads created: 6
Thread-0 packs order 1
Thread-1 packs order 2
Thread-4 packs order 5
Thread-5 packs order 6
Thread-2 packs order 3
Thread-3 packs order 4
Each order gets its own thread, Thread-0 to Thread-5. int n = order is needed because order changes, and a lambda can only use effectively final variables. Six is fine, but a thousand orders would mean a thousand threads started at once, and every thread costs memory and setup time.
Three workers, six orders
long start = System.currentTimeMillis();
// 3 workers, created once
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int order = 1; order <= 6; order++) {
int n = order; // a lambda needs a fixed copy
pool.submit(() -> pack(n)); // hand the order to the pool
}
pool.close(); // finish every order, then stop
long seconds = (System.currentTimeMillis() - start) / 1000;
System.out.println("6 orders in " + seconds + " seconds");
pool-1-thread-1 packs order 1
pool-1-thread-2 packs order 2
pool-1-thread-3 packs order 3
pool-1-thread-2 packs order 4
pool-1-thread-1 packs order 5
pool-1-thread-3 packs order 6
6 orders in 2 seconds
Executors.newFixedThreadPool(3) gives an ExecutorService with three workers that it creates once and keeps. submit puts each order in the pool's queue; no new thread starts for it. The three workers take orders 1, 2 and 3; orders 4, 5 and 6 wait and go to whichever worker is free next. Two rounds of one second: 2 seconds. close() waits for every order, then stops the workers. Delete it and the workers wait for more orders, so the program never ends.
Close the entrance, then wait
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int order = 1; order <= 5; order++) {
int n = order; // a lambda needs a fixed copy
pool.submit(() -> pack(n));
}
pool.shutdown(); // no NEW orders; the ones inside still run
System.out.println("after shutdown: done? " + pool.isTerminated());
// wait here, at most 1 minute
pool.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("after waiting: done? " + pool.isTerminated());
after shutdown: done? false
pool-1-thread-1 packed order 1
pool-1-thread-2 packed order 2
pool-1-thread-3 packed order 3
pool-1-thread-2 packed order 5
pool-1-thread-1 packed order 4
after waiting: done? true
Here pack prints after it sleeps. shutdown() closes the entrance: no new orders, but the ones inside still run, so isTerminated() is false straight after. awaitTermination waits (here up to a minute) for the orders inside to finish; then it's true. Submit order 6 after shutdown() and it's refused with RejectedExecutionException. close() does both steps in one call.
Same six orders, three pool sizes
static long packAll(int workers, int orders) {
long start = System.currentTimeMillis();
ExecutorService pool = Executors.newFixedThreadPool(workers);
for (int order = 1; order <= orders; order++) {
int n = order; // a lambda needs a fixed copy
pool.submit(() -> pack(n));
}
pool.close(); // wait until every order is packed
return (System.currentTimeMillis() - start) / 1000;
}
pool of 1: 6 orders in 6 seconds
pool of 3: 6 orders in 2 seconds
pool of 6: 6 orders in 1 seconds
One worker packs all six one after another. Three workers pack two each. Six workers give every order its own worker. More workers, less waiting, as long as your machine has the cores and the tasks are independent. A pool needs at least one worker: newFixedThreadPool(0) throws IllegalArgumentException.
Recap
| Call | What it does |
|---|---|
Executors.newFixedThreadPool(n) | n workers, created once and reused |
pool.submit(task) | puts a task in the queue |
pool.close() | waits for every task, then stops |
pool.shutdown() | no new tasks; the ones inside still run |
pool.awaitTermination(...) | waits for the tasks inside to finish |
A pool can also hand results back; see Callable, Future and CompletableFuture.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Concurrency: Processes, Threads and the Main Thread in Java
Every Java program runs as a process and starts on one thread, main. One cook takes 15 seconds for soup and salad; a second thread, Jack, brings it to 10. Then two threads add to one counter a million times each and count less than 2,000,000.
Creating Threads in Java: Thread, Runnable and Lambdas
Three ways to give a thread its job: an InvoiceMailer that extends Thread, a ReportTask record that implements Runnable, and a lambda. worker.run() prints main, worker.start() prints backup-worker, and two cashiers, Jack and Liam, scan items in an order that changes every run.
Java Thread Lifecycle: sleep, join and interrupt
A courier thread walks from NEW through RUNNABLE and TIMED_WAITING to TERMINATED while main WAITs at join. An interrupt wakes a sleeping download on report-3: one version retries it, the other returns. And a daemon status thread dies when the last user thread ends.
Java Race Conditions and synchronized
Two cashiers each sell a million tickets on one counter and the total comes out short, a different number every run, because sold++ is read, add, write. A synchronized method or a synchronized block on one shared lock gives exactly 2,000,000; a new Object() lock protects nothing.
