Executors Class in Java: Factory Methods for Thread Pools
Executors is a utility class of static factory methods. It creates ready-configured executors, such as fixed, cached and scheduled thread pools, so you do not have to call the ThreadPoolExecutor constructor yourself.
This tutorial lists what each factory method really returns, shows the helper methods for thread factories and Callable adapters, and explains when to avoid the factories.
1. What Is the Executors Class?
java.util.concurrent.Executors is a final class, added in Java 5, with no public constructor. It is not part of the executor inheritance hierarchy; it only creates and adapts the types described in the Executor Framework tutorial.
Its methods fall into four groups: executor factories, scheduled-executor factories, thread factories, and adapters that turn other task types into a Callable.
2. Factory Methods and What They Return
| Method | Returns |
|---|---|
newFixedThreadPool(n) | A ThreadPoolExecutor with n threads and an unbounded LinkedBlockingQueue. |
newCachedThreadPool() | A ThreadPoolExecutor that creates threads as needed, reuses idle ones, and removes threads unused for 60 seconds. |
newSingleThreadExecutor() | One worker thread and an unbounded queue, wrapped so it cannot be reconfigured to use more threads. |
newScheduledThreadPool(n) | A ScheduledThreadPoolExecutor. |
newSingleThreadScheduledExecutor() | A single-thread scheduler that cannot be reconfigured. |
newWorkStealingPool() | A ForkJoinPool using the number of available processors (Java 8+). |
newVirtualThreadPerTaskExecutor() | Starts a new virtual thread for each task (Java 21+). |
newThreadPerTaskExecutor(factory) | Starts a new thread from the given factory for each task (Java 21+). |
Most methods also have an overload that accepts a ThreadFactory.
3. Example: Inspecting What the Factories Create
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
public class FactoryInspection {
static void describe(String factory, ExecutorService executor) {
String type;
if (executor instanceof ScheduledThreadPoolExecutor) {
type = "ScheduledThreadPoolExecutor";
} else if (executor instanceof ThreadPoolExecutor pool) {
type = "ThreadPoolExecutor (core=" + pool.getCorePoolSize()
+ ", max=" + (pool.getMaximumPoolSize() == Integer.MAX_VALUE ? "unbounded" : pool.getMaximumPoolSize())
+ ", queue=" + pool.getQueue().getClass().getSimpleName() + ")";
} else if (executor instanceof ForkJoinPool) {
type = "ForkJoinPool";
} else {
type = "ExecutorService (implementation class not public)";
}
System.out.printf("%-34s -> %s%n", factory, type);
executor.close();
}
public static void main(String[] args) {
describe("newFixedThreadPool(4)", Executors.newFixedThreadPool(4));
describe("newCachedThreadPool()", Executors.newCachedThreadPool());
describe("newSingleThreadExecutor()", Executors.newSingleThreadExecutor());
describe("newScheduledThreadPool(2)", Executors.newScheduledThreadPool(2));
describe("newWorkStealingPool()", Executors.newWorkStealingPool());
describe("newVirtualThreadPerTaskExecutor()", Executors.newVirtualThreadPerTaskExecutor());
}
}
newFixedThreadPool(4) -> ThreadPoolExecutor (core=4, max=4, queue=LinkedBlockingQueue) newCachedThreadPool() -> ThreadPoolExecutor (core=0, max=unbounded, queue=SynchronousQueue) newSingleThreadExecutor() -> ExecutorService (implementation class not public) newScheduledThreadPool(2) -> ScheduledThreadPoolExecutor newWorkStealingPool() -> ForkJoinPool newVirtualThreadPerTaskExecutor() -> ExecutorService (implementation class not public)
How the code works
- Pattern matching for
instanceof(Java 16+) checks the real class of each executor and, for aThreadPoolExecutor, reads its configuration. - The fixed pool has equal core and maximum sizes and an unbounded queue; the cached pool starts with no threads and can grow without limit.
- The single-thread executor is deliberately hidden behind a wrapper, so it cannot be cast to
ThreadPoolExecutorand resized. - The virtual-thread executor uses an implementation class that is not part of the public API.
4. Example: Thread Factories and Callable Adapters
import java.util.List;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
public class NamedInvoiceWorkers {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// Java 21+ thread builder: threads named invoice-1, invoice-2, ...
ThreadFactory named = Thread.ofPlatform().name("invoice-", 1).factory();
// Executors.callable() adapts a Runnable into a Callable with a fixed result
Runnable archive = () -> { /* move PDFs to cold storage */ };
Callable<String> archiveTask = Executors.callable(archive, "archived");
try (ExecutorService pool = Executors.newFixedThreadPool(2, named)) {
List<Future<String>> results = pool.invokeAll(List.of(
() -> Thread.currentThread().getName(),
() -> Thread.currentThread().getName()));
TreeSet<String> threadNames = new TreeSet<>();
for (Future<String> f : results) {
threadNames.add(f.get());
}
System.out.println("Worker threads used: " + threadNames);
System.out.println("Adapted runnable returned: " + pool.submit(archiveTask).get());
}
}
}
Worker threads used: [invoice-1, invoice-2] Adapted runnable returned: archived
How the code works
Thread.ofPlatform().name("invoice-", 1).factory()(Java 21+) builds aThreadFactorythat names threads invoice-1, invoice-2 and so on, which makes logs and thread dumps easier to read.newFixedThreadPool(2, named)uses that factory for its two workers.Executors.callable(archive, "archived")wraps aRunnableas aCallablethat returns the fixed value.- The thread names are collected in a sorted set, because which task runs on which thread can differ between runs.
5. Other Helper Methods
| Method | Purpose |
|---|---|
defaultThreadFactory() | Creates non-daemon threads named pool-N-thread-M. |
callable(Runnable) | Adapts a Runnable into a Callable<Object> that returns null. |
unconfigurableExecutorService(es) | Wraps an executor so callers cannot cast it and change its settings. |
privilegedThreadFactory() | Deprecated for removal since Java 17, along with the other privileged methods. |
6. Common Mistakes and Best Practices
- Unbounded queues.
newFixedThreadPool()andnewSingleThreadExecutor()queue without limit; under sustained overload, memory use keeps growing. - Unbounded threads.
newCachedThreadPool()can create a very large number of platform threads during a burst of long tasks. - When to skip the factories. For production servers, create a ThreadPoolExecutor with a bounded queue and an explicit rejection policy.
- Blocking tasks on Java 21+. Prefer newVirtualThreadPerTaskExecutor() over large platform-thread pools.
- Shutting down. Every executor the factories create must still be shut down, ideally with try-with-resources.
7. Summary
Executorsis a final utility class of static factory methods; it is not itself an executor.- Fixed and cached pools are
ThreadPoolExecutorinstances; scheduled pools areScheduledThreadPoolExecutors. - Java 21 added
newVirtualThreadPerTaskExecutor()andnewThreadPerTaskExecutor(). - Fixed and single-thread factories use unbounded queues, so choose them deliberately.
Related Tutorials
8. References
Frequently Asked Questions (FAQ)
Q1. What does Executors.newFixedThreadPool() return?
A ThreadPoolExecutor whose core and maximum pool sizes both equal the given number, backed by an unbounded LinkedBlockingQueue.
Q2. What is the difference between newFixedThreadPool(1) and newSingleThreadExecutor()?
Both run tasks on one thread with an unbounded queue. The single-thread executor is wrapped so it is guaranteed not to be reconfigured to use additional threads, while a fixed pool can be cast to ThreadPoolExecutor and resized.
Q3. Is the Executors class deprecated?
No. Only the privileged methods, such as privilegedThreadFactory(), are deprecated for removal since Java 17. The regular factory methods are fully supported.
Q4. Why do some guides advise against Executors factory methods?
Because the fixed and single-thread factories use unbounded queues and the cached factory allows unbounded threads. Under heavy load either can exhaust memory, so servers often build a ThreadPoolExecutor with explicit limits instead.
Q5. Which factory method creates virtual threads?
Executors.newVirtualThreadPerTaskExecutor(), added in Java 21. It starts a new virtual thread for each submitted task instead of reusing a pool.