← ReJava · 学习目录

REJAVA / LEARNING NOTES

第 5 课 · JDK 21 线程池官方来源摘录

保留官方材料的来源与原文,区分接口保证和特定版本的实现。

Java 17 / 21更新于 2026.10.02约 9 分钟阅读

根据课程材料整理

本次更新说明
  • 整理官方依据,保留来源、版本和原文。

提取日期:2026-09-29。来源:本机 Eclipse Temurin 21.0.10 的 lib/src.zip,java.base/java/util/concurrent/ 下官方源文件;保留 Javadoc 原文及少量实现,便于核对课堂简化的边界。源码实现用于解释本版本,不将细节泛化为所有 Executor。

在线对应:ThreadPoolExecutor、ExecutorService、Future、Executors。

阅读索引:A–D 支持 7 参数、先队列后扩容、拒绝;E–G、I–J 支持提交方式、异常和关闭;H 支持固定池与缓存池的容量风险。课程参数估算是注明假设的教学推导,不是 JDK 官方推荐数值。可见性另见 jdk-official-docs-excerpts.md D 节。

A. ThreadPoolExecutor 类说明:容量、队列、回收与拒绝

An {@link ExecutorService} that executes each submitted task using one of possibly several pooled threads, normally configured using {@link Executors} factory methods.

Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each {@code ThreadPoolExecutor} also maintains some basic statistics, such as the number of completed tasks.

To be useful across a wide range of contexts, this class provides many adjustable parameters and extensibility hooks. However, programmers are urged to use the more convenient {@link Executors} factory methods {@link Executors#newCachedThreadPool} (unbounded thread pool, with automatic thread reclamation), {@link Executors#newFixedThreadPool} (fixed size thread pool) and {@link Executors#newSingleThreadExecutor} (single background thread), that preconfigure settings for the most common usage scenarios. Otherwise, use the following guide when manually configuring and tuning this class:

Core and maximum pool sizes
A {@code ThreadPoolExecutor} will automatically adjust the pool size (see {@link #getPoolSize}) according to the bounds set by corePoolSize (see {@link #getCorePoolSize}) and maximumPoolSize (see {@link #getMaximumPoolSize}).

When a new task is submitted in method {@link #execute(Runnable)}, if fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle. Else if fewer than maximumPoolSize threads are running, a new thread will be created to handle the request only if the queue is full. By setting corePoolSize and maximumPoolSize the same, you create a fixed-size thread pool. By setting maximumPoolSize to an essentially unbounded value such as {@code Integer.MAX_VALUE}, you allow the pool to accommodate an arbitrary number of concurrent tasks. Most typically, core and maximum pool sizes are set only upon construction, but they may also be changed dynamically using {@link #setCorePoolSize} and {@link #setMaximumPoolSize}.

On-demand construction
By default, even core threads are initially created and started only when new tasks arrive, but this can be overridden dynamically using method {@link #prestartCoreThread} or {@link #prestartAllCoreThreads}. You probably want to prestart threads if you construct the pool with a non-empty queue.
Creating new threads
New threads are created using a {@link ThreadFactory}. If not otherwise specified, a {@link Executors#defaultThreadFactory} is used, that creates threads to all be in the same {@link ThreadGroup} and with the same {@code NORM_PRIORITY} priority and non-daemon status. By supplying a different ThreadFactory, you can alter the thread's name, thread group, priority, daemon status, etc. If a {@code ThreadFactory} fails to create a thread when asked by returning null from {@code newThread}, the executor will continue, but might not be able to execute any tasks. Threads should possess the "modifyThread" {@code RuntimePermission}. If worker threads or other threads using the pool do not possess this permission, service may be degraded: configuration changes may not take effect in a timely manner, and a shutdown pool may remain in a state in which termination is possible but not completed.
Keep-alive times
If the pool currently has more than corePoolSize threads, excess threads will be terminated if they have been idle for more than the keepAliveTime (see {@link #getKeepAliveTime(TimeUnit)}). This provides a means of reducing resource consumption when the pool is not being actively used. If the pool becomes more active later, new threads will be constructed. This parameter can also be changed dynamically using method {@link #setKeepAliveTime(long, TimeUnit)}. Using a value of {@code Long.MAX_VALUE} {@link TimeUnit#NANOSECONDS} effectively disables idle threads from ever terminating prior to shut down. By default, the keep-alive policy applies only when there are more than corePoolSize threads, but method {@link #allowCoreThreadTimeOut(boolean)} can be used to apply this time-out policy to core threads as well, so long as the keepAliveTime value is non-zero.
Queuing
Any {@link BlockingQueue} may be used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing:
  • If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.
  • If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.
  • If a request cannot be queued, a new thread is created unless this would exceed maximumPoolSize, in which case, the task will be rejected.

There are three general strategies for queuing:

  1. Direct handoffs. A good default choice for a work queue is a {@link SynchronousQueue} that hands off tasks to threads without otherwise holding them. Here, an attempt to queue a task will fail if no threads are immediately available to run it, so a new thread will be constructed. This policy avoids lockups when handling sets of requests that might have internal dependencies. Direct handoffs generally require unbounded maximumPoolSizes to avoid rejection of new submitted tasks. This in turn admits the possibility of unbounded thread growth when commands continue to arrive on average faster than they can be processed.
  2. Unbounded queues. Using an unbounded queue (for example a {@link LinkedBlockingQueue} without a predefined capacity) will cause new tasks to wait in the queue when all corePoolSize threads are busy. Thus, no more than corePoolSize threads will ever be created. (And the value of the maximumPoolSize therefore doesn't have any effect.) This may be appropriate when each task is completely independent of others, so tasks cannot affect each others execution; for example, in a web page server. While this style of queuing can be useful in smoothing out transient bursts of requests, it admits the possibility of unbounded work queue growth when commands continue to arrive on average faster than they can be processed.
  3. Bounded queues. A bounded queue (for example, an {@link ArrayBlockingQueue}) helps prevent resource exhaustion when used with finite maximumPoolSizes, but can be more difficult to tune and control. Queue sizes and maximum pool sizes may be traded off for each other: Using large queues and small pools minimizes CPU usage, OS resources, and context-switching overhead, but can lead to artificially low throughput. If tasks frequently block (for example if they are I/O bound), a system may be able to schedule time for more threads than you otherwise allow. Use of small queues generally requires larger pool sizes, which keeps CPUs busier but may encounter unacceptable scheduling overhead, which also decreases throughput.
Rejected tasks
New tasks submitted in method {@link #execute(Runnable)} will be rejected when the Executor has been shut down, and also when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated. In either case, the {@code execute} method invokes the {@link RejectedExecutionHandler#rejectedExecution(Runnable, ThreadPoolExecutor)} method of its {@link RejectedExecutionHandler}. Four predefined handler policies are provided:
  1. In the default {@link ThreadPoolExecutor.AbortPolicy}, the handler throws a runtime {@link RejectedExecutionException} upon rejection.
  2. In {@link ThreadPoolExecutor.CallerRunsPolicy}, the thread that invokes {@code execute} itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.
  3. In {@link ThreadPoolExecutor.DiscardPolicy}, a task that cannot be executed is simply dropped. This policy is designed only for those rare cases in which task completion is never relied upon.
  4. In {@link ThreadPoolExecutor.DiscardOldestPolicy}, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.) This policy is rarely acceptable. In nearly all cases, you should also cancel the task to cause an exception in any component waiting for its completion, and/or log the failure, as illustrated in {@link ThreadPoolExecutor.DiscardOldestPolicy} documentation.

It is possible to define and use other kinds of {@link RejectedExecutionHandler} classes. Doing so requires some care especially when policies are designed to work only under particular capacity or queuing policies.

Hook methods
This class provides {@code protected} overridable {@link #beforeExecute(Thread, Runnable)} and {@link #afterExecute(Runnable, Throwable)} methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method {@link #terminated} can be overridden to perform any special processing that needs to be done once the Executor has fully terminated.

If hook, callback, or BlockingQueue methods throw exceptions, internal worker threads may in turn fail, abruptly terminate, and possibly be replaced.

Queue maintenance
Method {@link #getQueue()} allows access to the work queue for purposes of monitoring and debugging. Use of this method for any other purpose is strongly discouraged. Two supplied methods, {@link #remove(Runnable)} and {@link #purge} are available to assist in storage reclamation when large numbers of queued tasks become cancelled.
Reclamation
A pool that is no longer referenced in a program AND has no remaining threads may be reclaimed (garbage collected) without being explicitly shutdown. You can configure a pool to allow all unused threads to eventually die by setting appropriate keep-alive times, using a lower bound of zero core threads and/or setting {@link #allowCoreThreadTimeOut(boolean)}.

B. 七参数构造器及入参约束

Creates a new {@code ThreadPoolExecutor} with the given initial parameters.

@param corePoolSize the number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set @param maximumPoolSize the maximum number of threads to allow in the pool @param keepAliveTime when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. @param unit the time unit for the {@code keepAliveTime} argument @param workQueue the queue to use for holding tasks before they are executed. This queue will hold only the {@code Runnable} tasks submitted by the {@code execute} method. @param threadFactory the factory to use when the executor creates a new thread @param handler the handler to use when execution is blocked because the thread bounds and queue capacities are reached @throws IllegalArgumentException if one of the following holds:
{@code corePoolSize < 0}
{@code keepAliveTime < 0}
{@code maximumPoolSize <= 0}
{@code maximumPoolSize < corePoolSize} @throws NullPointerException if {@code workQueue} or {@code threadFactory} or {@code handler} is null

C. execute 的实际分支

public void execute(Runnable command) { if (command == null) throw new NullPointerException(); /* * Proceed in 3 steps: * * 1. If fewer than corePoolSize threads are running, try to * start a new thread with the given command as its first * task. The call to addWorker atomically checks runState and * workerCount, and so prevents false alarms that would add * threads when it shouldn’t, by returning false. * * 2. If a task can be successfully queued, then we still need * to double-check whether we should have added a thread * (because existing ones died since last checking) or that * the pool shut down since entry into this method. So we * recheck state and if necessary roll back the enqueuing if * stopped, or start a new thread if there are none. * * 3. If we cannot queue task, then we try to add a new * thread. If it fails, we know we are shut down or saturated * and so reject the task. */ int c = ctl.get(); if (workerCountOf(c) < corePoolSize) { if (addWorker(command, true)) return; c = ctl.get(); } if (isRunning(c) && workQueue.offer(command)) { int recheck = ctl.get(); if (! isRunning(recheck) && remove(command)) reject(command); else if (workerCountOf(recheck) == 0) addWorker(null, false); } else if (!addWorker(command, false)) reject(command); }

D. CallerRunsPolicy 在关闭后的行为

public static class CallerRunsPolicy implements RejectedExecutionHandler { /** * Creates a {@code CallerRunsPolicy}. */ public CallerRunsPolicy() { }

    /**
     * Executes task r in the caller's thread, unless the executor
     * has been shut down, in which case the task is discarded.
     *
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        if (!e.isShutdown()) {
            r.run();
        }
    }
}

E. ExecutorService:提交、结果和关闭

An {@link Executor} that provides methods to manage termination and methods that can produce a {@link Future} for tracking progress of one or more asynchronous tasks.

An {@code ExecutorService} can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an {@code ExecutorService}. The {@link #shutdown} method will allow previously submitted tasks to execute before terminating, while the {@link #shutdownNow} method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused {@code ExecutorService} should be shut down to allow reclamation of its resources.

Method {@code submit} extends base method {@link Executor#execute(Runnable)} by creating and returning a {@link Future} that can be used to cancel execution and/or wait for completion. Methods {@code invokeAny} and {@code invokeAll} perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class {@link ExecutorCompletionService} can be used to write customized variants of these methods.)

The {@link Executors} class provides factory methods for the executor services provided in this package.

Usage Examples

Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured {@link Executors#newFixedThreadPool} factory method:

 {@code
class NetworkService implements Runnable {
  private final ServerSocket serverSocket;
  private final ExecutorService pool;

  public NetworkService(int port, int poolSize)
      throws IOException {
    serverSocket = new ServerSocket(port);
    pool = Executors.newFixedThreadPool(poolSize);
  }

  public void run() { // run the service
    try {
      for (;;) {
        pool.execute(new Handler(serverSocket.accept()));
      }
    } catch (IOException ex) {
      pool.shutdown();
    }
  }
}

class Handler implements Runnable {
  private final Socket socket;
  Handler(Socket socket) { this.socket = socket; }
  public void run() {
    // read and service request on socket
  }
}}

An {@code ExecutorService} may also be established and closed (shutdown, blocking until terminated) as follows; illustrating with a different {@code Executors} factory method:

 {@code
try (ExecutorService e =  Executors.newWorkStealingPool()) {
  // submit or execute many tasks with e ...
}}

Further customization is also possible. For example, the following method shuts down an {@code ExecutorService} in two phases, first by calling {@code shutdown} to reject incoming tasks, and then calling {@code shutdownNow}, if necessary, to cancel any lingering tasks:

 {@code
void shutdownAndAwaitTermination(ExecutorService pool) {
  pool.shutdown(); // Disable new tasks from being submitted
  try {
    // Wait a while for existing tasks to terminate
    if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
      pool.shutdownNow(); // Cancel currently executing tasks
      // Wait a while for tasks to respond to being cancelled
      if (!pool.awaitTermination(60, TimeUnit.SECONDS))
          System.err.println("Pool did not terminate");
    }
  } catch (InterruptedException ex) {
    // (Re-)Cancel if current thread also interrupted
    pool.shutdownNow();
    // Preserve interrupt status
    Thread.currentThread().interrupt();
  }
}}

Memory consistency effects: Actions in a thread prior to the submission of a {@code Runnable} or {@code Callable} task to an {@code ExecutorService} happen-before any actions taken by that task, which in turn happen-before the result is retrieved via {@code Future.get()}.

@since 1.5 @author Doug Lea

F. shutdown / shutdownNow / awaitTermination 文档

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. Invocation has no additional effect if already shut down.

This method does not wait for previously submitted tasks to complete execution. Use {@link #awaitTermination awaitTermination} to do that.

@throws SecurityException if a security manager exists and shutting down this ExecutorService may manipulate threads that the caller is not permitted to modify because it does not hold {@link java.lang.RuntimePermission}{@code (“modifyThread”)}, or the security manager’s {@code checkAccess} method denies access.

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

This method does not wait for actively executing tasks to terminate. Use {@link #awaitTermination awaitTermination} to do that.

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via {@link Thread#interrupt}, so any task that fails to respond to interrupts may never terminate.

@return list of tasks that never commenced execution @throws SecurityException if a security manager exists and shutting down this ExecutorService may manipulate threads that the caller is not permitted to modify because it does not hold {@link java.lang.RuntimePermission}{@code (“modifyThread”)}, or the security manager’s {@code checkAccess} method denies access.

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

@param timeout the maximum time to wait @param unit the time unit of the timeout argument @return {@code true} if this executor terminated and {@code false} if the timeout elapsed before termination @throws InterruptedException if interrupted while waiting

G. Future.get:超时与异常

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

@param timeout the maximum time to wait @param unit the time unit of the timeout argument @return the computed result @throws CancellationException if the computation was cancelled @throws ExecutionException if the computation threw an exception @throws InterruptedException if the current thread was interrupted while waiting @throws TimeoutException if the wait timed out

H. 常用工厂的配置

public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); }

public static ExecutorService newSingleThreadExecutor() { return newSingleThreadExecutor(defaultThreadFactory()); }

public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue()); }

I. submit 如何包装并执行任务

public Future submit(Callable task) { if (task == null) throw new NullPointerException(); RunnableFuture ftask = newTaskFor(task); execute(ftask); return ftask; }

J. afterExecute 对 execute / submit 异常的说明

Method invoked upon completion of execution of the given Runnable. This method is invoked by the thread that executed the task. If non-null, the Throwable is the uncaught {@code RuntimeException} or {@code Error} that caused execution to terminate abruptly.

This implementation does nothing, but may be customized in subclasses. Note: To properly nest multiple overridings, subclasses should generally invoke {@code super.afterExecute} at the beginning of this method.

Note: When actions are enclosed in tasks (such as {@link FutureTask}) either explicitly or via methods such as {@code submit}, these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method. If you would like to trap both kinds of failures in this method, you can further probe for such cases, as in this sample subclass that prints either the direct cause or the underlying exception if a task has been aborted:

 {@code
class ExtendedExecutor extends ThreadPoolExecutor {
  // ...
  protected void afterExecute(Runnable r, Throwable t) {
    super.afterExecute(r, t);
    if (t == null
        && r instanceof Future
        && ((Future)r).isDone()) {
      try {
        Object result = ((Future) r).get();
      } catch (CancellationException ce) {
        t = ce;
      } catch (ExecutionException ee) {
        t = ee.getCause();
      } catch (InterruptedException ie) {
        // ignore/reset
        Thread.currentThread().interrupt();
      }
    }
    if (t != null)
      System.out.println(t);
  }
}}

@param r the runnable that has completed @param t the exception that caused termination, or null if execution completed normally

K. 任务类型、提交结果与取消语义

Runnable.run

Runs this operation.

Callable.call

Computes a result, or throws an exception if unable to do so.

@return computed result @throws Exception if unable to compute a result

ExecutorService.submit(Runnable)

Submits a Runnable task for execution and returns a Future representing that task. The Future’s {@code get} method will return {@code null} upon successful completion.

@param task the task to submit @return a Future representing pending completion of the task @throws RejectedExecutionException if the task cannot be scheduled for execution @throws NullPointerException if the task is null

Future.cancel

Attempts to cancel execution of this task. This method has no effect if the task is already completed or cancelled, or could not be cancelled for some other reason. Otherwise, if this task has not started when {@code cancel} is called, this task should never run. If the task has already started, then the {@code mayInterruptIfRunning} parameter determines whether the thread executing this task (when known by the implementation) is interrupted in an attempt to stop the task.

The return value from this method does not necessarily indicate whether the task is now cancelled; use {@link #isCancelled}.

@param mayInterruptIfRunning {@code true} if the thread executing this task should be interrupted (if the thread is known to the implementation); otherwise, in-progress tasks are allowed to complete @return {@code false} if the task could not be cancelled, typically because it has already completed; {@code true} otherwise. If two or more threads cause a task to be cancelled, then at least one of them returns {@code true}. Implementations may provide stronger guarantees.

L. 队列容量

LinkedBlockingQueue 默认构造

Creates a {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}.

SynchronousQueue 类说明

A {@linkplain BlockingQueue blocking queue} in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one. You cannot {@code peek} at a synchronous queue because an element is only present when you try to remove it; you cannot insert an element (using any method) unless another thread is trying to remove it; you cannot iterate as there is nothing to iterate. The head of the queue is the element that the first queued inserting thread is trying to add to the queue; if there is no such queued thread then no element is available for removal and {@code poll()} will return {@code null}. For purposes of other {@code Collection} methods (for example {@code contains}), a {@code SynchronousQueue} acts as an empty collection. This queue does not permit {@code null} elements.

Synchronous queues are similar to rendezvous channels used in CSP and Ada. They are well suited for handoff designs, in which an object running in one thread must sync up with an object running in another thread in order to hand it some information, event, or task.

This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to {@code true} grants threads access in FIFO order.

This class and its iterator implement all of the optional methods of the {@link Collection} and {@link Iterator} interfaces.

This class is a member of the Java Collections Framework.

@since 1.5 @author Doug Lea and Bill Scherer and Michael Scott @param the type of elements held in this queue