REJAVA / LEARNING NOTES
CompletableFuture(可编排的异步结果)官方摘录
保留官方材料的来源与原文,区分接口保证和特定版本的实现。
根据课程材料整理
本次更新说明
- 整理官方依据,保留来源、版本和原文。
来源:Temurin 21.0.10 JDK 自带的 lib/src.zip(java.base/java/util/concurrent);2026-10-05 摘录。CompletableFuture 与 CompletionStage 的类说明另与 Azul 17.0.14 的源码对比:CompletableFuture 类说明逐字相同,CompletionStage 只多一行 @param 标注;ForkJoinPool 公共池的默认并行度在 17 与 21 都是 max(1, 处理器数 - 1)。实现说明不是跨版本接口承诺。
官方文档:CompletableFuture · CompletionStage · ForkJoinPool
A. CompletableFuture 类说明:非 async 方法由谁执行、默认线程池、cancel、get 与 join 的异常
/**
* A {@link Future} that may be explicitly completed (setting its
* value and status), and may be used as a {@link CompletionStage},
* supporting dependent functions and actions that trigger upon its
* completion.
*
* <p>When two or more threads attempt to
* {@link #complete complete},
* {@link #completeExceptionally completeExceptionally}, or
* {@link #cancel cancel}
* a CompletableFuture, only one of them succeeds.
*
* <p>In addition to these and related methods for directly
* manipulating status and results, CompletableFuture implements
* interface {@link CompletionStage} with the following policies: <ul>
*
* <li>Actions supplied for dependent completions of
* <em>non-async</em> methods may be performed by the thread that
* completes the current CompletableFuture, or by any other caller of
* a completion method.
*
* <li>All <em>async</em> methods without an explicit Executor
* argument are performed using the {@link ForkJoinPool#commonPool()}
* (unless it does not support a parallelism level of at least two, in
* which case, a new Thread is created to run each task). This may be
* overridden for non-static methods in subclasses by defining method
* {@link #defaultExecutor()}. To simplify monitoring, debugging,
* and tracking, all generated asynchronous tasks are instances of the
* marker interface {@link AsynchronousCompletionTask}. Operations
* with time-delays can use adapter methods defined in this class, for
* example: {@code supplyAsync(supplier, delayedExecutor(timeout,
* timeUnit))}. To support methods with delays and timeouts, this
* class maintains at most one daemon thread for triggering and
* cancelling actions, not for running them.
*
* <li>All CompletionStage methods are implemented independently of
* other public methods, so the behavior of one method is not impacted
* by overrides of others in subclasses.
*
* <li>All CompletionStage methods return CompletableFutures. To
* restrict usages to only those methods defined in interface
* CompletionStage, use method {@link #minimalCompletionStage}. Or to
* ensure only that clients do not themselves modify a future, use
* method {@link #copy}.
* </ul>
*
* <p>CompletableFuture also implements {@link Future} with the following
* policies: <ul>
*
* <li>Since (unlike {@link FutureTask}) this class has no direct
* control over the computation that causes it to be completed,
* cancellation is treated as just another form of exceptional
* completion. Method {@link #cancel cancel} has the same effect as
* {@code completeExceptionally(new CancellationException())}. Method
* {@link #isCompletedExceptionally} can be used to determine if a
* CompletableFuture completed in any exceptional fashion.
*
* <li>In case of exceptional completion with a CompletionException,
* methods {@link #get()} and {@link #get(long, TimeUnit)} throw an
* {@link ExecutionException} with the same cause as held in the
* corresponding CompletionException. To simplify usage in most
* contexts, this class also defines methods {@link #join()} and
* {@link #getNow} that instead throw the CompletionException directly
* in these cases.
* </ul>
*
* <p>Arguments used to pass a completion result (that is, for
* parameters of type {@code T}) for methods accepting them may be
* null, but passing a null value for any other parameter will result
* in a {@link NullPointerException} being thrown.
*
* <p>Subclasses of this class should normally override the "virtual
* constructor" method {@link #newIncompleteFuture}, which establishes
* the concrete type returned by CompletionStage methods. For example,
* here is a class that substitutes a different default Executor and
* disables the {@code obtrude} methods:
*
* <pre> {@code
* class MyCompletableFuture<T> extends CompletableFuture<T> {
* static final Executor myExecutor = ...;
* public MyCompletableFuture() { }
* public <U> CompletableFuture<U> newIncompleteFuture() {
* return new MyCompletableFuture<U>(); }
* public Executor defaultExecutor() {
* return myExecutor; }
* public void obtrudeValue(T value) {
* throw new UnsupportedOperationException(); }
* public void obtrudeException(Throwable ex) {
* throw new UnsupportedOperationException(); }
* }}</pre>
*
* @author Doug Lea
* @param <T> The result type returned by this future's {@code join}
* and {@code get} methods
* @since 1.8
*/
B. CompletionStage 类说明:apply/accept/run、compose、then/combine/either、三种执行方式、异常传播
/**
* A stage of a possibly asynchronous computation, that performs an
* action or computes a value when another CompletionStage completes.
* A stage completes upon termination of its computation, but this may
* in turn trigger other dependent stages. The functionality defined
* in this interface takes only a few basic forms, which expand out to
* a larger set of methods to capture a range of usage styles:
*
* <ul>
*
* <li>The computation performed by a stage may be expressed as a
* Function, Consumer, or Runnable (using methods with names including
* <em>apply</em>, <em>accept</em>, or <em>run</em>, respectively)
* depending on whether it requires arguments and/or produces results.
* For example:
* <pre> {@code
* stage.thenApply(x -> square(x))
* .thenAccept(x -> System.out.print(x))
* .thenRun(() -> System.out.println());}</pre>
*
* An additional form (<em>compose</em>) allows the construction of
* computation pipelines from functions returning completion stages.
*
* <p>Any argument to a stage's computation is the outcome of a
* triggering stage's computation.
*
* <li>One stage's execution may be triggered by completion of a
* single stage, or both of two stages, or either of two stages.
* Dependencies on a single stage are arranged using methods with
* prefix <em>then</em>. Those triggered by completion of
* <em>both</em> of two stages may <em>combine</em> their results or
* effects, using correspondingly named methods. Those triggered by
* <em>either</em> of two stages make no guarantees about which of the
* results or effects are used for the dependent stage's computation.
*
* <li>Dependencies among stages control the triggering of
* computations, but do not otherwise guarantee any particular
* ordering. Additionally, execution of a new stage's computations may
* be arranged in any of three ways: default execution, default
* asynchronous execution (using methods with suffix <em>async</em>
* that employ the stage's default asynchronous execution facility),
* or custom (via a supplied {@link Executor}). The execution
* properties of default and async modes are specified by
* CompletionStage implementations, not this interface. Methods with
* explicit Executor arguments may have arbitrary execution
* properties, and might not even support concurrent execution, but
* are arranged for processing in a way that accommodates asynchrony.
*
* <li>Two method forms ({@link #handle handle} and {@link
* #whenComplete whenComplete}) support unconditional computation
* whether the triggering stage completed normally or exceptionally.
* Method {@link #exceptionally exceptionally} supports computation
* only when the triggering stage completes exceptionally, computing a
* replacement result, similarly to the java {@code catch} keyword.
* In all other cases, if a stage's computation terminates abruptly
* with an (unchecked) exception or error, then all dependent stages
* requiring its completion complete exceptionally as well, with a
* {@link CompletionException} holding the exception as its cause. If
* a stage is dependent on <em>both</em> of two stages, and both
* complete exceptionally, then the CompletionException may correspond
* to either one of these exceptions. If a stage is dependent on
* <em>either</em> of two others, and only one of them completes
* exceptionally, no guarantees are made about whether the dependent
* stage completes normally or exceptionally. In the case of method
* {@code whenComplete}, when the supplied action itself encounters an
* exception, then the stage completes exceptionally with this
* exception unless the source stage also completed exceptionally, in
* which case the exceptional completion from the source stage is
* given preference and propagated to the dependent stage.
*
* </ul>
*
* <p>All methods adhere to the above triggering, execution, and
* exceptional completion specifications (which are not repeated in
* individual method specifications). Additionally, while arguments
* used to pass a completion result (that is, for parameters of type
* {@code T}) for methods accepting them may be null, passing a null
* value for any other parameter will result in a {@link
* NullPointerException} being thrown.
*
* <p>Method form {@link #handle handle} is the most general way of
* creating a continuation stage, unconditionally performing a
* computation that is given both the result and exception (if any) of
* the triggering CompletionStage, and computing an arbitrary result.
* Method {@link #whenComplete whenComplete} is similar, but preserves
* the result of the triggering stage instead of computing a new one.
* Because a stage's normal result may be {@code null}, both methods
* should have a computation structured thus:
*
* <pre>{@code (result, exception) -> {
* if (exception == null) {
* // triggering stage completed normally
* } else {
* // triggering stage completed exceptionally
* }
* }}</pre>
*
* <p>This interface does not define methods for initially creating,
* forcibly completing normally or exceptionally, probing completion
* status or results, or awaiting completion of a stage.
* Implementations of CompletionStage may provide means of achieving
* such effects, as appropriate. Method {@link #toCompletableFuture}
* enables interoperability among different implementations of this
* interface by providing a common conversion type.
*
* @param <T> the type of values the stage produces or consumes
*
* @author Doug Lea
* @since 1.8
*/
C. 单个方法说明
/**
* Returns a new CompletionStage that, when this stage completes
* normally, is executed with this stage's result as the argument
* to the supplied function.
*
* <p>This method is analogous to
* {@link java.util.Optional#map Optional.map} and
* {@link java.util.stream.Stream#map Stream.map}.
*
* <p>See the {@link CompletionStage} documentation for rules
* covering exceptional completion.
*
* @param fn the function to use to compute the value of the
* returned CompletionStage
* @param <U> the function's return type
* @return the new CompletionStage
*/
public <U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn);
/**
* Returns a new CompletionStage that is completed with the same
* value as the CompletionStage returned by the given function.
*
* <p>When this stage completes normally, the given function is
* invoked with this stage's result as the argument, returning
* another CompletionStage. When that stage completes normally,
* the CompletionStage returned by this method is completed with
* the same value.
*
* <p>To ensure progress, the supplied function must arrange
* eventual completion of its result.
*
* <p>This method is analogous to
* {@link java.util.Optional#flatMap Optional.flatMap} and
* {@link java.util.stream.Stream#flatMap Stream.flatMap}.
*
* <p>See the {@link CompletionStage} documentation for rules
* covering exceptional completion.
*
* @param fn the function to use to compute another CompletionStage
* @param <U> the type of the returned CompletionStage's result
* @return the new CompletionStage
*/
public <U> CompletionStage<U> thenCompose
/**
* Returns a new CompletionStage that, when this and the other
* given stage both complete normally, is executed with the two
* results as arguments to the supplied function.
*
* See the {@link CompletionStage} documentation for rules
* covering exceptional completion.
*
* @param other the other CompletionStage
* @param fn the function to use to compute the value of the
* returned CompletionStage
* @param <U> the type of the other CompletionStage's result
* @param <V> the function's return type
* @return the new CompletionStage
*/
public <U,V> CompletionStage<V> thenCombine
/**
* Returns a new CompletionStage that, when this stage completes
* either normally or exceptionally, is executed with this stage's
* result and exception as arguments to the supplied function.
*
* <p>When this stage is complete, the given function is invoked
* with the result (or {@code null} if none) and the exception (or
* {@code null} if none) of this stage as arguments, and the
* function's result is used to complete the returned stage.
*
* @param fn the function to use to compute the value of the
* returned CompletionStage
* @param <U> the function's return type
* @return the new CompletionStage
*/
public <U> CompletionStage<U> handle
* Returns a new CompletionStage that, when this stage completes
* exceptionally, is executed with this stage's exception as the
* argument to the supplied function. Otherwise, if this stage
* completes normally, then the returned stage also completes
* normally with the same value.
*
* @param fn the function to use to compute the value of the
* returned CompletionStage if this CompletionStage completed
* exceptionally
* @return the new CompletionStage
*/
public CompletionStage<T> exceptionally
/**
* Returns a new CompletionStage with the same result or exception as
* this stage, that executes the given action when this stage completes.
*
* <p>When this stage is complete, the given action is invoked
* with the result (or {@code null} if none) and the exception (or
* {@code null} if none) of this stage as arguments. The returned
* stage is completed when the action returns.
*
* <p>Unlike method {@link #handle handle},
* this method is not designed to translate completion outcomes,
* so the supplied action should not throw an exception. However,
* if it does, the following rules apply: if this stage completed
* normally but the supplied action throws an exception, then the
* returned stage completes exceptionally with the supplied
* action's exception. Or, if this stage completed exceptionally
* and the supplied action throws an exception, then the returned
* stage completes exceptionally with this stage's exception.
*
* @param action the action to perform
* @return the new CompletionStage
*/
public CompletionStage<T> whenComplete
/**
* Returns a new CompletableFuture that is asynchronously completed
* by a task running in the {@link ForkJoinPool#commonPool()} with
* the value obtained by calling the given Supplier.
*
* @param supplier a function returning the value to be used
* to complete the returned CompletableFuture
* @param <U> the function's return type
* @return the new CompletableFuture
*/
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
return asyncSupplyStage(ASYNC_POOL, supplier);
}
/**
* Returns a new CompletableFuture that is asynchronously completed
* by a task running in the given executor with the value obtained
* by calling the given Supplier.
*
* @param supplier a function returning the value to be used
* to complete the returned CompletableFuture
* @param executor the executor to use for asynchronous execution
* @param <U> the function's return type
* @return the new CompletableFuture
*/
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
Executor executor) {
return asyncSupplyStage(screenExecutor(executor), supplier);
}
/**
* Returns the result value when complete, or throws an
* (unchecked) exception if completed exceptionally. To better
* conform with the use of common functional forms, if a
* computation involved in the completion of this
* CompletableFuture threw an exception, this method throws an
* (unchecked) {@link CompletionException} with the underlying
* exception as its cause.
*
* @return the result value
* @throws CancellationException if the computation was cancelled
* @throws CompletionException if this future completed
* exceptionally or a completion computation threw an exception
*/
@SuppressWarnings("unchecked")
public T join() {
Object r;
if ((r = result) == null)
/**
* Returns a new CompletableFuture that is completed when all of
* the given CompletableFutures complete. If any of the given
* CompletableFutures complete exceptionally, then the returned
* CompletableFuture also does so, with a CompletionException
* holding this exception as its cause. Otherwise, the results,
* if any, of the given CompletableFutures are not reflected in
* the returned CompletableFuture, but may be obtained by
* inspecting them individually. If no CompletableFutures are
* provided, returns a CompletableFuture completed with the value
* {@code null}.
*
* <p>Among the applications of this method is to await completion
* of a set of independent CompletableFutures before continuing a
* program, as in: {@code CompletableFuture.allOf(c1, c2,
* c3).join();}.
*
* @param cfs the CompletableFutures
* @return a new CompletableFuture that is completed when all of the
* given CompletableFutures complete
* @throws NullPointerException if the array or any of its elements are
* {@code null}
*/
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
return andTree(cfs, 0, cfs.length - 1);
}
/**
* If not already completed, completes this CompletableFuture with
* a {@link CancellationException}. Dependent CompletableFutures
* that have not already completed will also complete
* exceptionally, with a {@link CompletionException} caused by
* this {@code CancellationException}.
*
* @param mayInterruptIfRunning this value has no effect in this
* implementation because interrupts are not used to control
* processing.
*
* @return {@code true} if this task is now cancelled
*/
public boolean cancel(boolean mayInterruptIfRunning) {
/**
* Exceptionally completes this CompletableFuture with
* a {@link TimeoutException} if not otherwise completed
* before the given timeout.
*
* @param timeout how long to wait before completing exceptionally
* with a TimeoutException, in units of {@code unit}
* @param unit a {@code TimeUnit} determining how to interpret the
* {@code timeout} parameter
* @return this CompletableFuture
* @since 9
*/
public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit) {
D. ForkJoinPool 公共池:说明、默认并行度、工作线程是守护线程
* <p>A static {@link #commonPool()} is available and appropriate for
* most applications. The common pool is used by any ForkJoinTask that
* is not explicitly submitted to a specified pool. Using the common
* pool normally reduces resource usage (its threads are slowly
* reclaimed during periods of non-use, and reinstated upon subsequent
* use).
*
/**
* Returns the common pool instance. This pool is statically
* constructed; its run state is unaffected by attempts to {@link
* #shutdown} or {@link #shutdownNow}. However this pool and any
* ongoing processing are automatically terminated upon program
* {@link System#exit}. Any program that relies on asynchronous
* task processing to complete before program termination should
* invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
* before exit.
*
* @return the common pool instance
* @since 1.8
*/
public static ForkJoinPool commonPool() {
// 公共池构造方法中(Java 21;Java 17 的 ForkJoinPool 中为同一表达式 Math.max(1, availableProcessors() - 1)):
if (preset == 0)
pc = Math.max(1, Runtime.getRuntime().availableProcessors() - 1);
// ForkJoinWorkerThread 构造方法中:
super.setDaemon(true);
对照:未通过系统属性指定时,公共池目标并行度=处理器数-1(至少 1);它的工作线程是守护线程,所以 main 结束时,没被等待的异步任务可能来不及执行完。