Executors.newFixedThreadPool()
Creates a pool with a given number of threads.
Available since: Java 1.5
Syntax
public static ExecutorService newFixedThreadPool(int nThreads)Parameters
| Parameter | Type | Description |
|---|---|---|
| nThreads | int | The 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:
500000500000Notes
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
- ExecutorService — A service that runs tasks on a pool of threads.
- Executors.newVirtualThreadPerTaskExecutor() — Creates a service that runs every task in its own virtual thread.
- ExecutorService.submit() — Sends a task to the pool and immediately returns a `Future` for its result.
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.