Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Executors — creating a fixed-size thread pool

java.util.concurrent.Executors provides factory methods for task executors. Executors.newFixedThreadPool limits the number of active worker threads, but not the queue size. Learn how to retrieve results and close the pool in Java SE 21.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

ExecutorService pool = Executors.newFixedThreadPool(nThreads);

java.util.concurrent.Executors is a utility class with factory methods for task executors. Executors.newFixedThreadPool(nThreads) returns an ExecutorService that reuses threads; at most nThreads of them process tasks simultaneously. For nThreads <= 0, the method throws IllegalArgumentException.

Excess tasks wait in a shared, unbounded queue. A fixed thread count therefore does not bound the memory used by pending tasks: sustained overload can increase it. Do not assume task completion order.

submit returns a Future; get() waits for the result and can throw ExecutionException if the task fails with an exception, or InterruptedException if the wait is interrupted. The example prints results in a fixed order because the main thread prints them, rather than the worker tasks.

In Java SE 21, ExecutorService supports try-with-resources: close() initiates shutdown and waits for tasks to finish. Calling shutdown() alone does not wait. A task that never finishes can therefore delay leaving the block. This entry targets Java SE 21; the production runtime has not been attested.

Examples

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
    public static void main(String[] args) throws Exception {
        try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
            Future<Integer> first = pool.submit(() -> 6 * 7);
            Future<Integer> second = pool.submit(() -> 10 + 5);

            System.out.println(first.get());
            System.out.println(second.get());
        }
    }
}

Result

42
15

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources