Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Executors.newFixedThreadPool — fixed-size thread pool

A pool of size 3 can handle at most three tasks concurrently. It does not make them start at the same instant. Additional tasks wait in a queue when all workers are busy.

Version: Java SE 21

Syntax

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

// Static methods declared by Executors:
public static ExecutorService newFixedThreadPool(int nThreads)
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory)

// Example call:
ExecutorService pool = Executors.newFixedThreadPool(3);

Executors.newFixedThreadPool is a static factory method on java.util.concurrent.Executors. It returns an ExecutorService that reuses worker threads across tasks. Executors.newFixedThreadPool(3) lets at most three tasks be in progress at once. That is an upper bound, not a promise that three tasks start at the same instant, run in physical parallel, or finish in submission order.

When all workers are busy, additional tasks wait in a shared unbounded queue. The pool size limits workers, not the number of queued tasks. If work keeps arriving faster than the pool completes it, the queue can consume more and more memory. If you need to cap the backlog, use a ThreadPoolExecutor with a bounded queue and a deliberately chosen rejection policy.

The overload taking only int nThreads uses the default factory, which creates non-daemon threads. The ThreadFactory overload uses the supplied factory to create workers as needed. Both throw IllegalArgumentException for nThreads <= 0; the second also throws NullPointerException if the factory is null. If a worker dies because of a failure before shutdown, the pool replaces it if needed to run later tasks.

Shut down the pool when you no longer need it: default workers can keep the JVM alive. shutdown() stops accepting new tasks but lets submitted tasks run and does not wait for termination. In Java SE 21, try-with-resources calls close(), which initiates shutdown and waits for the executor to terminate.

Examples

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FixedPoolDemo {
    public static void main(String[] args)
            throws InterruptedException, ExecutionException {
        CountDownLatch started = new CountDownLatch(3);
        CountDownLatch release = new CountDownLatch(1);

        try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
            Callable<Void> holdWorker = () -> {
                started.countDown();
                release.await();
                return null;
            };

            Future<Integer> fourth;
            try {
                for (int i = 0; i < 3; i++) {
                    pool.submit(holdWorker);
                }
                started.await();
                fourth = pool.submit(() -> 4);
                System.out.println("Fourth task done before release: " + fourth.isDone());
            } finally {
                release.countDown();
            }
            System.out.println("Fourth task result: " + fourth.get());
        }
    }
}

Result

Fourth task done before release: false
Fourth task result: 4

Each of the first three tasks occupies a worker and cannot finish until released. The fourth task’s `isDone()` therefore returns `false`. After release, `get()` waits if necessary for the result `4`. The example shows that tasks overlap, not that they start at the same instant.

Related lessons

  • Java · Lesson 50 · Intermediate · Version: 2

Sources