Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ThreadPoolExecutor: a bounded pool and CallerRunsPolicy

ThreadPoolExecutor manages a worker pool and a task queue. Learn when it creates threads or queues work, how ThreadPoolExecutor.CallerRunsPolicy handles overload, and how shutdown() and awaitTermination() support orderly termination.

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

Syntax

new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, new ThreadPoolExecutor.CallerRunsPolicy());
executor.execute(task);
executor.shutdown();
executor.awaitTermination(timeout, unit);

ThreadPoolExecutor executes tasks using pooled threads. On submission, it creates a thread if the worker count is below corePoolSize; otherwise, it tries queuing. When the queue is full, it can create a thread up to maximumPoolSize, then applies the rejection policy. An unbounded queue normally prevents growth beyond corePoolSize and can accumulate an unbounded backlog.

ThreadPoolExecutor.CallerRunsPolicy runs a rejected task synchronously in the thread calling execute, unless the executor has been shut down. This slows the task producer but may block a request-handling thread, for example. The pool limit does not include these caller-thread executions. After shutdown, this policy silently discards the task rather than throwing, so it does not guarantee execution.

ThreadPoolExecutor.shutdown initiates orderly shutdown: previously accepted tasks execute, but new tasks are not accepted. It does not wait for completion; use awaitTermination and check its result. shutdownNow() only attempts interruption, so tasks must respond to interrupts. The example uses a latch rather than delays to force overload. Scope: Java SE 21; repository runtime, production runtime not attested.

Examples

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch release = new CountDownLatch(1);
        AtomicInteger completed = new AtomicInteger();
        Thread caller = Thread.currentThread();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                1, 1, 0L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(1),
                new ThreadPoolExecutor.CallerRunsPolicy());

        try {
            executor.execute(() -> {
                try {
                    release.await();
                    completed.incrementAndGet();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
            executor.execute(() -> completed.incrementAndGet());
            executor.execute(() -> {
                System.out.println("caller thread: "
                        + (Thread.currentThread() == caller));
                completed.incrementAndGet();
            });
        } finally {
            release.countDown();
            executor.shutdown();
        }

        try {
            if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                executor.shutdownNow();
                throw new IllegalStateException("Termination timed out");
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt();
            throw e;
        }
        System.out.println("completed: " + completed.get());
    }
}

Result

caller thread: true
completed: 3

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