00:00

Executors Class in Java: Factory Methods for Thread Pools

Last updated:

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

MethodReturns
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

FactoryInspection.java
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());
    }
}
Output
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

  1. Pattern matching for instanceof (Java 16+) checks the real class of each executor and, for a ThreadPoolExecutor, reads its configuration.
  2. 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.
  3. The single-thread executor is deliberately hidden behind a wrapper, so it cannot be cast to ThreadPoolExecutor and resized.
  4. The virtual-thread executor uses an implementation class that is not part of the public API.

4. Example: Thread Factories and Callable Adapters

NamedInvoiceWorkers.java
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());
        }
    }
}
Output
Worker threads used: [invoice-1, invoice-2]
Adapted runnable returned: archived

How the code works

  1. Thread.ofPlatform().name("invoice-", 1).factory() (Java 21+) builds a ThreadFactory that names threads invoice-1, invoice-2 and so on, which makes logs and thread dumps easier to read.
  2. newFixedThreadPool(2, named) uses that factory for its two workers.
  3. Executors.callable(archive, "archived") wraps a Runnable as a Callable that returns the fixed value.
  4. The thread names are collected in a sorted set, because which task runs on which thread can differ between runs.

5. Other Helper Methods

MethodPurpose
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() and newSingleThreadExecutor() 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

  • Executors is a final utility class of static factory methods; it is not itself an executor.
  • Fixed and cached pools are ThreadPoolExecutor instances; scheduled pools are ScheduledThreadPoolExecutors.
  • Java 21 added newVirtualThreadPerTaskExecutor() and newThreadPerTaskExecutor().
  • Fixed and single-thread factories use unbounded queues, so choose them deliberately.

Related Tutorials

8. References