Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Fixed thread pools, queue capacity, and orderly shutdown

Create two pools with two workers each, compare their queue limits, and collect task results before calling `shutdown()` on both pools.

Version: Java SE 21

Syntax

In java.util.concurrent:
public static ExecutorService Executors.newFixedThreadPool(int nThreads)
public static ExecutorService Executors.newFixedThreadPool(int nThreads, ThreadFactory threadFactory)
void ExecutorService.shutdown()
public void ThreadPoolExecutor.shutdown()

Bounded-queue alternative:
new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(2), new ThreadPoolExecutor.AbortPolicy())

In Java SE 21, the static Executors.newFixedThreadPool(2) method in java.util.concurrent returns an ExecutorService that reuses worker threads. At most two workers process tasks at once; when both are busy, further tasks wait in a shared queue with no configured capacity limit. The worker limit therefore does not bound the backlog. If tasks arrive faster than the pool finishes them, the queue can grow and use more memory.

The Executors.newFixedThreadPool(nThreads, threadFactory) overload uses the supplied ThreadFactory to create workers but does not bound the queue. Both overloads throw IllegalArgumentException for nThreads <= 0; the second throws NullPointerException if the factory is null.

To limit the backlog, configure a ThreadPoolExecutor with both core and maximum pool sizes set to 2 and an ArrayBlockingQueue<>(2). In this configuration, up to two tasks can run on workers and up to two more can wait in the queue. If the pool cannot accept a task because both workers are busy and the queue is full, AbortPolicy throws RejectedExecutionException instead of waiting for space. It also rejects submissions after shutdown begins.

ExecutorService.shutdown() defines the orderly shutdown contract, and ThreadPoolExecutor.shutdown() implements it: previously accepted tasks can run, new tasks are rejected, and the call returns without waiting for completion. Repeating the call has no further effect. A SecurityException is possible if an active security manager denies permission. On the normal path, collect every required result with Future.get() before shutting down both pools in finally, which also handles cleanup on failure. get() waits for a particular task if needed; to wait for the whole pool with a time limit after shutdown(), use awaitTermination().

Examples

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class PoolDemo {
    public static void main(String[] args)
            throws InterruptedException, ExecutionException {
        ExecutorService fixed = Executors.newFixedThreadPool(2);
        ThreadPoolExecutor bounded = new ThreadPoolExecutor(
                2, 2, 0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(2), new ThreadPoolExecutor.AbortPolicy());

        try {
            Future<Integer> first = fixed.submit(() -> 2);
            Future<Integer> second = fixed.submit(() -> 3);
            Future<Integer> third = bounded.submit(() -> 5);
            Future<Integer> fourth = bounded.submit(() -> 7);

            int fixedSum = first.get() + second.get();
            int boundedSum = third.get() + fourth.get();
            System.out.println("fixed=" + fixedSum + ", bounded=" + boundedSum);
        } finally {
            try {
                fixed.shutdown();
            } finally {
                bounded.shutdown();
            }
        }
    }
}

Result

fixed=5, bounded=12

The program submits two tasks to each pool and collects all four results before shutdown on the normal path. It prints only the two sums, one per pool, in a fixed order regardless of worker scheduling. It does not force queue saturation or task rejection.

Related lessons

  • Java · Lesson 42 · Advanced · Version: 2

Sources