Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Executors.newFixedThreadPool()

Creates a pool with a given number of threads.

Available since: Java 1.5

Syntax

public static ExecutorService newFixedThreadPool(int nThreads)

Parameters

ParameterTypeDescription
nThreadsintThe number of threads in the pool.

Return value

ExecutorServiceA pool with a fixed number of threads.

Examples

A pool sized by CPU cores for computation:

void main() throws Exception {
    int cores = Runtime.getRuntime().availableProcessors();
    try (var pool = Executors.newFixedThreadPool(cores)) {
        Future<Long> sum = pool.submit(() -> LongStream.rangeClosed(1, 1_000_000).sum());
        IO.println(sum.get());
    }
}

Output:

500000500000

Notes

If there are more tasks than threads, the extra ones wait in a queue. For computation the number of threads usually equals the number of cores (availableProcessors()). For tasks that mostly wait (network, files), newVirtualThreadPerTaskExecutor() is handier.

See also

Related recipes

In the tutorial

  • Thread pools and ExecutorService — ExecutorService in Java — thread pools, submit, Callable and Future, invokeAll, handling errors in tasks, timeouts and closing the pool.

Thanks for reading!

Donate to the site — we work hard for you.