ExecutorService and Thread Pool Types
Create fixed, cached, single, and scheduled thread pools and understand when to use each.
ExecutorService and Thread Pool Types is a free Java Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Use Thread Pools?
Creating a new Thread for every task is expensive — thread creation and destruction has overhead. A thread pool reuses a fixed set of threads to execute many tasks, reducing overhead and controlling resource consumption.
import java.util.concurrent.*;
// Bad practice: new thread per task
new Thread(() -> System.out.println("task")).start();
// Better: reuse threads from a pool
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> System.out.println("task from pool"));
pool.shutdown();newFixedThreadPool
Creates a pool with exactly N threads. Extra tasks queue up until a thread becomes available. Good when you know the desired parallelism level.
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
final int taskId = i;
pool.submit(() -> {
System.out.println("Task " + taskId + " on " + Thread.currentThread().getName());
});
}
pool.shutdown();
pool.awaitTermination(10, TimeUnit.SECONDS);newCachedThreadPool
Creates threads on demand and reuses idle ones. Threads idle for 60 seconds are terminated. Good for many short-lived tasks; risky for long-running or unlimited tasks (can exhaust memory).
ExecutorService cached = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
cached.submit(() -> {
// quick task
double result = Math.sqrt(Math.random());
});
}
cached.shutdown();newSingleThreadExecutor
A pool with exactly one thread. Tasks execute sequentially in submission order. Good for serializing access to a shared resource.
ExecutorService single = Executors.newSingleThreadExecutor();
single.submit(() -> System.out.println("Task 1"));
single.submit(() -> System.out.println("Task 2"));
single.submit(() -> System.out.println("Task 3"));
// Always prints: Task 1, Task 2, Task 3 (sequential)
single.shutdown();newScheduledThreadPool
Supports scheduled and recurring tasks. Use for polling, retries, and background maintenance.
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
// One-shot delay
scheduler.schedule(() -> System.out.println("Delayed!"),
3, TimeUnit.SECONDS);
// Fixed rate (every 2 seconds)
scheduler.scheduleAtFixedRate(
() -> System.out.println("Tick"),
0, 2, TimeUnit.SECONDS);
// Run later: scheduler.shutdown();VirtualThreadExecutor (Java 21+)
Java 21 introduces virtual threads — lightweight, cheap to create. Use Executors.newVirtualThreadPerTaskExecutor() for I/O-heavy workloads:
// Java 21+
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
final int id = i;
exec.submit(() -> {
Thread.sleep(100); // blocks without tying up OS thread
System.out.println("vthread " + id);
});
}
} // auto-shutdownChoosing the Right Pool
Guidelines:
- CPU-bound tasks: Fixed pool with N = number of CPU cores
- I/O-bound tasks: Cached pool or virtual threads
- Sequential tasks: Single thread executor
- Scheduled/recurring: Scheduled thread pool
int cores = Runtime.getRuntime().availableProcessors();
ExecutorService cpuPool = Executors.newFixedThreadPool(cores);
System.out.println("Pool size: " + cores);Custom ThreadPoolExecutor
For fine-grained control, create a ThreadPoolExecutor directly:
ThreadPoolExecutor tpe = new ThreadPoolExecutor(
2, // corePoolSize
10, // maximumPoolSize
60L, // keepAliveTime
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100), // work queue
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy() // rejection policy
);
tpe.submit(() -> System.out.println("Custom pool task"));
tpe.shutdown();Graceful Shutdown
Always shut down ExecutorService to release threads. shutdown() stops accepting new tasks but completes queued ones. shutdownNow() attempts to cancel running tasks.
ExecutorService pool = Executors.newFixedThreadPool(4);
// ... submit tasks ...
pool.shutdown(); // no new tasks
try {
if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
pool.shutdownNow(); // force cancel
}
} catch (InterruptedException e) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}ExecutorService as AutoCloseable (Java 19+)
In Java 19+, ExecutorService implements AutoCloseable. Use try-with-resources for automatic shutdown:
// Java 19+ (preview), Java 21 stable
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
pool.submit(() -> System.out.println("task"));
} // pool.close() called: waits for tasks then shuts downRejection Policies
When the pool is saturated (all threads busy, queue full), the rejection policy handles the overflow:
- AbortPolicy (default): throws
RejectedExecutionException - CallerRunsPolicy: caller thread runs the task
- DiscardPolicy: silently drops the task
- DiscardOldestPolicy: drops oldest queued task
Quick Check
You have a CPU-bound task that performs heavy computation. How many threads should your fixed thread pool have?
Recap: ExecutorService & Thread Pools
Key takeaways:
- Fixed pool: fixed N threads; extra tasks queue
- Cached pool: grows on demand; idle threads expire after 60s
- Single thread: serial execution order guaranteed
- Scheduled pool: delayed and recurring tasks
- Always shutdown(); awaitTermination() for clean exit
Frequently asked questions
Is the “ExecutorService and Thread Pool Types” lesson free?
Yes — the full text of “ExecutorService and Thread Pool Types” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “ExecutorService and Thread Pool Types”?
Create fixed, cached, single, and scheduled thread pools and understand when to use each. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “ExecutorService and Thread Pool Types” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- ExecutorService and Thread Pool Types
- Submitting Tasks: Runnable vs Callable
- Future and Error Handling
- ScheduledExecutorService for Recurring Tasks