深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()

异步计算

  • 所谓异步调用其实就是实现一个可无需等待被调用函数的返回值而让操作继续运行的方法。在 Java 语言中,简单的讲就是另启一个线程来完成调用中的部分计算,使调用继续运行或返回,而不需要等待计算结果。但调用者仍需要取线程的计算结果。

  • JDK5新增了Future接口,用于描述一个异步计算的结果。虽然 Future 以及相关使用方法提供了异步执行任务的能力,但是对于结果的获取却是很不方便,只能通过阻塞或者轮询的方式得到任务的结果。阻塞的方式显然和我们的异步编程的初衷相违背,轮询的方式又会耗费无谓的 CPU 资源,而且也不能及时地得到计算结果。

  • 以前我们获取一个异步任务的结果可能是这样写的

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()_第1张图片

Future 接口的局限性

Future接口可以构建异步应用,但依然有其局限性。它很难直接表述多个Future 结果之间的依赖性。实际开发中,我们经常需要达成以下目的:

  1. 将多个异步计算的结果合并成一个

  2. 等待Future集合中的所有任务都完成

  3. Future完成事件(即,任务完成以后触发执行动作)

  4. 。。。

函数式编程

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()_第2张图片

CompletionStage

  • CompletionStage代表异步计算过程中的某一个阶段,一个阶段完成以后可能会触发另外一个阶段

  • 一个阶段的计算执行可以是一个Function,Consumer或者Runnable。比如:stage.thenApply(x -> square(x)).thenAccept(x -> System.out.print(x)).thenRun(() -> System.out.println())

  • 一个阶段的执行可能是被单个阶段的完成触发,也可能是由多个阶段一起触发

CompletableFuture

  • 在Java8中,CompletableFuture提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,并且提供了函数式编程的能力,可以通过回调的方式处理计算结果,也提供了转换和组合 CompletableFuture 的方法。
  • 它可能代表一个明确完成的Future,也有可能代表一个完成阶段( CompletionStage ),它支持在计算完成以后触发一些函数或执行某些动作。
  • 它实现了Future和CompletionStage接口

创建CompletableFuture

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()_第3张图片

thenApply

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()_第4张图片

当前阶段正常完成以后执行,而且当前阶段的执行的结果会作为下一阶段的输入参数。thenApplyAsync默认是异步执行的。这里所谓的异步指的是不在当前线程内执行。

thenApply相当于回调函数(callback)

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()_第5张图片

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()_第6张图片

thenAccept与thenRun

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()_第7张图片

  • 可以看到,thenAccept和thenRun都是无返回值的。如果说thenApply是不停的输入输出的进行生产,那么thenAccept和thenRun就是在进行消耗。它们是整个计算的最后两个阶段。
  • 同样是执行指定的动作,同样是消耗,二者也有区别:

    • thenAccept接收上一阶段的输出作为本阶段的输入   

    • thenRun根本不关心前一阶段的输出,根本不不关心前一阶段的计算结果,因为它不需要输入参数

thenCombine整合两个计算结果

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()_第8张图片

例如,此阶段与其它阶段一起完成,进而触发下一阶段:

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()_第9张图片

whenComplete

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()_第10张图片

例子

深入学习java源码之CompletableFuture.reportGet()与CompletableFuture.supplyAsync()_第11张图片

事实上,如果每个操作都很简单的话(比如:上面的例子中按照id去查)没有必要用这种多线程异步的方式,因为创建线程还需要时间,还不如直接同步执行来得快。

事实证明,只有当每个操作很复杂需要花费相对很长的时间(比如,调用多个其它的系统的接口;比如,商品详情页面这种需要从多个系统中查数据显示的)的时候用CompletableFuture才合适,不然区别真的不大,还不如顺序同步执行。

java源码

Modifier and Type Method and Description
CompletableFuture acceptEither(CompletionStage other, Consumer action)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,执行相应的结果作为提供的操作的参数。

CompletableFuture acceptEitherAsync(CompletionStage other, Consumer action)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,将使用此阶段的默认异步执行工具执行,其中相应的结果作为提供的操作的参数。

CompletableFuture acceptEitherAsync(CompletionStage other, Consumer action, Executor executor)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,将使用提供的执行器执行,其中相应的结果作为参数提供给函数。

static CompletableFuture allOf(CompletableFuture... cfs)

返回一个新的CompletableFuture,当所有给定的CompletableFutures完成时,完成。

static CompletableFuture anyOf(CompletableFuture... cfs)

返回一个新的CompletableFuture,当任何一个给定的CompletableFutures完成时,完成相同的结果。

CompletableFuture applyToEither(CompletionStage other, Function fn)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,执行相应的结果作为提供的函数的参数。

CompletableFuture applyToEitherAsync(CompletionStage other, Function fn)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,将使用此阶段的默认异步执行工具执行,其中相应的结果作为提供函数的参数。

CompletableFuture applyToEitherAsync(CompletionStage other, Function fn, Executor executor)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,将使用提供的执行器执行,其中相应的结果作为参数提供给函数。

boolean cancel(boolean mayInterruptIfRunning)

如果尚未完成,请使用CancellationException完成此CompletableFuture 。

boolean complete(T value)

如果不是已经完成,将返回的值 get()种相关方法为给定值。

static CompletableFuture completedFuture(U value)

返回已经使用给定值完成的新的CompletableFuture。

boolean completeExceptionally(Throwable ex)

如果尚未完成,则调用 get()和相关方法来抛出给定的异常。

CompletableFuture exceptionally(Function fn)

返回一个新的CompletableFuture,当CompletableFuture完成时完成,结果是异常触发此CompletableFuture的完成特殊功能的给定功能; 否则,如果此CompletableFuture正常完成,则返回的CompletableFuture也会以相同的值正常完成。

T get()

等待这个未来完成的必要,然后返回结果。

T get(long timeout, TimeUnit unit)

如果有必要等待这个未来完成的给定时间,然后返回其结果(如果有的话)。

T getNow(T valueIfAbsent)

如果已完成,则返回结果值(或抛出任何遇到的异常),否则返回给定的值IfAbsent。

int getNumberOfDependents()

返回完成等待完成此CompletableFuture的CompletableFutures的估计数。

CompletableFuture handle(BiFunction fn)

返回一个新的CompletionStage,当此阶段正常或异常完成时,将使用此阶段的结果和异常作为所提供函数的参数执行。

CompletableFuture handleAsync(BiFunction fn)

返回一个新的CompletionStage,当该阶段完成正常或异常时,将使用此阶段的默认异步执行工具执行,此阶段的结果和异常作为提供函数的参数。

CompletableFuture handleAsync(BiFunction fn, Executor executor)

返回一个新的CompletionStage,当此阶段完成正常或异常时,将使用提供的执行程序执行此阶段的结果和异常作为提供的函数的参数。

boolean isCancelled()

如果此CompletableFuture在正常完成之前被取消,则返回 true

boolean isCompletedExceptionally()

如果此CompletableFuture以任何方式完成异常完成,则返回 true

boolean isDone()

退货 true如果以任何方式完成:通常,特别地,或通过取消。

T join()

完成后返回结果值,如果完成异常,则返回(未检查)异常。

void obtrudeException(Throwable ex)

强制导致后续调用方法 get()和相关方法抛出给定的异常,无论是否已经完成。

void obtrudeValue(T value)

强制设置或重置随后方法返回的值 get()和相关方法,无论是否已经完成。

CompletableFuture runAfterBoth(CompletionStage other, Runnable action)

返回一个新的CompletionStage,当这个和另一个给定的阶段都正常完成时,执行给定的动作。

CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action)

返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,使用此阶段的默认异步执行工具执行给定的操作。

CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action, Executor executor)

返回一个新CompletionStage,当这和其他特定阶段正常完成,使用附带的执行见执行给定的动作CompletionStage覆盖特殊的完成规则的文档。

CompletableFuture runAfterEither(CompletionStage other, Runnable action)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,执行给定的操作。

CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,使用此阶段的默认异步执行工具执行给定的操作。

CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action, Executor executor)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,使用提供的执行器执行给定的操作。

static CompletableFuture runAsync(Runnable runnable)

返回一个新的CompletableFuture,它在运行给定操作后由运行在 ForkJoinPool.commonPool()中的任务 异步完成。

static CompletableFuture runAsync(Runnable runnable, Executor executor)

返回一个新的CompletableFuture,它在运行给定操作之后由在给定执行程序中运行的任务异步完成。

static CompletableFuture supplyAsync(Supplier supplier)

返回一个新的CompletableFuture,它通过在 ForkJoinPool.commonPool()中运行的任务与通过调用给定的供应商获得的值 异步完成。

static CompletableFuture supplyAsync(Supplier supplier, Executor executor)

返回一个新的CompletableFuture,由给定执行器中运行的任务异步完成,并通过调用给定的供应商获得的值。

CompletableFuture thenAccept(Consumer action)

返回一个新的CompletionStage,当此阶段正常完成时,将以该阶段的结果作为提供的操作的参数执行。

CompletableFuture thenAcceptAsync(Consumer action)

返回一个新的CompletionStage,当此阶段正常完成时,将使用此阶段的默认异步执行工具执行,此阶段的结果作为提供的操作的参数。

CompletableFuture thenAcceptAsync(Consumer action, Executor executor)

返回一个新的CompletionStage,当此阶段正常完成时,将使用提供的执行程序执行此阶段的结果作为提供的操作的参数。

CompletableFuture thenAcceptBoth(CompletionStage other, BiConsumer action)

返回一个新的CompletionStage,当这个和另一个给定的阶段都正常完成时,两个结果作为提供的操作的参数被执行。

CompletableFuture thenAcceptBothAsync(CompletionStage other, BiConsumer action)

返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,将使用此阶段的默认异步执行工具执行,其中两个结果作为提供的操作的参数。

CompletableFuture thenAcceptBothAsync(CompletionStage other, BiConsumer action, Executor executor)

返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,使用提供的执行器执行,其中两个结果作为提供的函数的参数。

CompletableFuture thenApply(Function fn)

返回一个新的CompletionStage,当此阶段正常完成时,将以该阶段的结果作为所提供函数的参数执行。

CompletableFuture thenApplyAsync(Function fn)

返回一个新的CompletionStage,当该阶段正常完成时,将使用此阶段的默认异步执行工具执行此阶段的结果作为所提供函数的参数。

CompletableFuture thenApplyAsync(Function fn, Executor executor)

返回一个新的CompletionStage,当此阶段正常完成时,将使用提供的执行程序执行此阶段的结果作为提供函数的参数。

CompletableFuture thenCombine(CompletionStage other, BiFunction fn)

返回一个新的CompletionStage,当这个和另一个给定的阶段都正常完成时,两个结果作为提供函数的参数执行。

CompletableFuture thenCombineAsync(CompletionStage other, BiFunction fn)

返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,将使用此阶段的默认异步执行工具执行,其中两个结果作为提供函数的参数。

CompletableFuture thenCombineAsync(CompletionStage other, BiFunction fn, Executor executor)

返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,使用提供的执行器执行,其中两个结果作为提供的函数的参数。

CompletableFuture thenCompose(Function> fn)

返回一个新的CompletionStage,当这个阶段正常完成时,这个阶段将作为提供函数的参数执行。

CompletableFuture thenComposeAsync(Function> fn)

返回一个新的CompletionStage,当此阶段正常完成时,将使用此阶段的默认异步执行工具执行,此阶段作为提供的函数的参数。

CompletableFuture thenComposeAsync(Function> fn, Executor executor)

返回一个新的CompletionStage,当此阶段正常完成时,将使用提供的执行程序执行此阶段的结果作为提供函数的参数。

CompletableFuture thenRun(Runnable action)

返回一个新的CompletionStage,当此阶段正常完成时,执行给定的操作。

CompletableFuture thenRunAsync(Runnable action)

返回一个新的CompletionStage,当此阶段正常完成时,使用此阶段的默认异步执行工具执行给定的操作。

CompletableFuture thenRunAsync(Runnable action, Executor executor)

返回一个新的CompletionStage,当此阶段正常完成时,使用提供的执行程序执行给定的操作。

CompletableFuture toCompletableFuture()

返回此CompletableFuture

String toString()

返回一个标识此CompletableFuture的字符串及其完成状态。

CompletableFuture whenComplete(BiConsumer action)

返回与此阶段相同的结果或异常的新的CompletionStage,当此阶段完成时,使用结果(或 null如果没有))和此阶段的异常(或 null如果没有))执行给定的操作。

CompletableFuture whenCompleteAsync(BiConsumer action)

返回一个与此阶段相同结果或异常的新CompletionStage,当此阶段完成时,执行给定操作将使用此阶段的默认异步执行工具执行给定操作,结果(或 null如果没有))和异常(或 null如果没有)这个阶段作为参数。

CompletableFuture whenCompleteAsync(BiConsumer action, Executor executor)

返回与此阶段相同的结果或异常的新的CompletionStage,当此阶段完成时,使用提供的执行者执行给定的操作,如果没有,则使用结果(或 null如果没有))和异常(或 null如果没有))作为论据。

package java.util.concurrent;
import java.util.function.Supplier;
import java.util.function.Consumer;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.BiFunction;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.locks.LockSupport;

public class CompletableFuture implements Future, CompletionStage {

    volatile Object result;       // Either the result or boxed AltResult
    volatile Completion stack;    // Top of Treiber stack of dependent actions

    final boolean internalComplete(Object r) { // CAS from null to r
        return UNSAFE.compareAndSwapObject(this, RESULT, null, r);
    }

    final boolean casStack(Completion cmp, Completion val) {
        return UNSAFE.compareAndSwapObject(this, STACK, cmp, val);
    }

    /** Returns true if successfully pushed c onto stack. */
    final boolean tryPushStack(Completion c) {
        Completion h = stack;
        lazySetNext(c, h);
        return UNSAFE.compareAndSwapObject(this, STACK, h, c);
    }

    final void pushStack(Completion c) {
        do {} while (!tryPushStack(c));
    }

    /* ------------- Encoding and decoding outcomes -------------- */

    static final class AltResult { // See above
        final Throwable ex;        // null only for NIL
        AltResult(Throwable x) { this.ex = x; }
    }

    /** The encoding of the null value. */
    static final AltResult NIL = new AltResult(null);

    /** Completes with the null value, unless already completed. */
    final boolean completeNull() {
        return UNSAFE.compareAndSwapObject(this, RESULT, null,
                                           NIL);
    }

    /** Returns the encoding of the given non-exceptional value. */
    final Object encodeValue(T t) {
        return (t == null) ? NIL : t;
    }

    /** Completes with a non-exceptional result, unless already completed. */
    final boolean completeValue(T t) {
        return UNSAFE.compareAndSwapObject(this, RESULT, null,
                                           (t == null) ? NIL : t);
    }

    static AltResult encodeThrowable(Throwable x) {
        return new AltResult((x instanceof CompletionException) ? x :
                             new CompletionException(x));
    }

    /** Completes with an exceptional result, unless already completed. */
    final boolean completeThrowable(Throwable x) {
        return UNSAFE.compareAndSwapObject(this, RESULT, null,
                                           encodeThrowable(x));
    }

    static Object encodeThrowable(Throwable x, Object r) {
        if (!(x instanceof CompletionException))
            x = new CompletionException(x);
        else if (r instanceof AltResult && x == ((AltResult)r).ex)
            return r;
        return new AltResult(x);
    }

    final boolean completeThrowable(Throwable x, Object r) {
        return UNSAFE.compareAndSwapObject(this, RESULT, null,
                                           encodeThrowable(x, r));
    }

    Object encodeOutcome(T t, Throwable x) {
        return (x == null) ? (t == null) ? NIL : t : encodeThrowable(x);
    }

    static Object encodeRelay(Object r) {
        Throwable x;
        return (((r instanceof AltResult) &&
                 (x = ((AltResult)r).ex) != null &&
                 !(x instanceof CompletionException)) ?
                new AltResult(new CompletionException(x)) : r);
    }

    final boolean completeRelay(Object r) {
        return UNSAFE.compareAndSwapObject(this, RESULT, null,
                                           encodeRelay(r));
    }

    private static  T reportGet(Object r)
        throws InterruptedException, ExecutionException {
        if (r == null) // by convention below, null means interrupted
            throw new InterruptedException();
        if (r instanceof AltResult) {
            Throwable x, cause;
            if ((x = ((AltResult)r).ex) == null)
                return null;
            if (x instanceof CancellationException)
                throw (CancellationException)x;
            if ((x instanceof CompletionException) &&
                (cause = x.getCause()) != null)
                x = cause;
            throw new ExecutionException(x);
        }
        @SuppressWarnings("unchecked") T t = (T) r;
        return t;
    }

    private static  T reportJoin(Object r) {
        if (r instanceof AltResult) {
            Throwable x;
            if ((x = ((AltResult)r).ex) == null)
                return null;
            if (x instanceof CancellationException)
                throw (CancellationException)x;
            if (x instanceof CompletionException)
                throw (CompletionException)x;
            throw new CompletionException(x);
        }
        @SuppressWarnings("unchecked") T t = (T) r;
        return t;
    }

    /* ------------- Async task preliminaries -------------- */
    public static interface AsynchronousCompletionTask {
    }

    private static final boolean useCommonPool =
        (ForkJoinPool.getCommonPoolParallelism() > 1);

    private static final Executor asyncPool = useCommonPool ?
        ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();

    /** Fallback if ForkJoinPool.commonPool() cannot support parallelism */
    static final class ThreadPerTaskExecutor implements Executor {
        public void execute(Runnable r) { new Thread(r).start(); }
    }

    static Executor screenExecutor(Executor e) {
        if (!useCommonPool && e == ForkJoinPool.commonPool())
            return asyncPool;
        if (e == null) throw new NullPointerException();
        return e;
    }

    // Modes for Completion.tryFire. Signedness matters.
    static final int SYNC   =  0;
    static final int ASYNC  =  1;
    static final int NESTED = -1;

    /* ------------- Base Completion classes and operations -------------- */

    @SuppressWarnings("serial")
    abstract static class Completion extends ForkJoinTask
        implements Runnable, AsynchronousCompletionTask {
        volatile Completion next;      // Treiber stack link

        abstract CompletableFuture tryFire(int mode);

        /** Returns true if possibly still triggerable. Used by cleanStack. */
        abstract boolean isLive();

        public final void run()                { tryFire(ASYNC); }
        public final boolean exec()            { tryFire(ASYNC); return true; }
        public final Void getRawResult()       { return null; }
        public final void setRawResult(Void v) {}
    }

    static void lazySetNext(Completion c, Completion next) {
        UNSAFE.putOrderedObject(c, NEXT, next);
    }

    final void postComplete() {
        CompletableFuture f = this; Completion h;
        while ((h = f.stack) != null ||
               (f != this && (h = (f = this).stack) != null)) {
            CompletableFuture d; Completion t;
            if (f.casStack(h, t = h.next)) {
                if (t != null) {
                    if (f != this) {
                        pushStack(h);
                        continue;
                    }
                    h.next = null;    // detach
                }
                f = (d = h.tryFire(NESTED)) == null ? this : d;
            }
        }
    }

    /** Traverses stack and unlinks dead Completions. */
    final void cleanStack() {
        for (Completion p = null, q = stack; q != null;) {
            Completion s = q.next;
            if (q.isLive()) {
                p = q;
                q = s;
            }
            else if (p == null) {
                casStack(q, s);
                q = stack;
            }
            else {
                p.next = s;
                if (p.isLive())
                    q = s;
                else {
                    p = null;  // restart
                    q = stack;
                }
            }
        }
    }

    /* ------------- One-input Completions -------------- */

    /** A Completion with a source, dependent, and executor. */
    @SuppressWarnings("serial")
    abstract static class UniCompletion extends Completion {
        Executor executor;                 // executor to use (null if none)
        CompletableFuture dep;          // the dependent to complete
        CompletableFuture src;          // source for action

        UniCompletion(Executor executor, CompletableFuture dep,
                      CompletableFuture src) {
            this.executor = executor; this.dep = dep; this.src = src;
        }

        final boolean claim() {
            Executor e = executor;
            if (compareAndSetForkJoinTaskTag((short)0, (short)1)) {
                if (e == null)
                    return true;
                executor = null; // disable
                e.execute(this);
            }
            return false;
        }

        final boolean isLive() { return dep != null; }
    }

    /** Pushes the given completion (if it exists) unless done. */
    final void push(UniCompletion c) {
        if (c != null) {
            while (result == null && !tryPushStack(c))
                lazySetNext(c, null); // clear on failure
        }
    }

    final CompletableFuture postFire(CompletableFuture a, int mode) {
        if (a != null && a.stack != null) {
            if (mode < 0 || a.result == null)
                a.cleanStack();
            else
                a.postComplete();
        }
        if (result != null && stack != null) {
            if (mode < 0)
                return this;
            else
                postComplete();
        }
        return null;
    }

    @SuppressWarnings("serial")
    static final class UniApply extends UniCompletion {
        Function fn;
        UniApply(Executor executor, CompletableFuture dep,
                 CompletableFuture src,
                 Function fn) {
            super(executor, dep, src); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d; CompletableFuture a;
            if ((d = dep) == null ||
                !d.uniApply(a = src, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; fn = null;
            return d.postFire(a, mode);
        }
    }

    final  boolean uniApply(CompletableFuture a,
                               Function f,
                               UniApply c) {
        Object r; Throwable x;
        if (a == null || (r = a.result) == null || f == null)
            return false;
        tryComplete: if (result == null) {
            if (r instanceof AltResult) {
                if ((x = ((AltResult)r).ex) != null) {
                    completeThrowable(x, r);
                    break tryComplete;
                }
                r = null;
            }
            try {
                if (c != null && !c.claim())
                    return false;
                @SuppressWarnings("unchecked") S s = (S) r;
                completeValue(f.apply(s));
            } catch (Throwable ex) {
                completeThrowable(ex);
            }
        }
        return true;
    }

    private  CompletableFuture uniApplyStage(
        Executor e, Function f) {
        if (f == null) throw new NullPointerException();
        CompletableFuture d =  new CompletableFuture();
        if (e != null || !d.uniApply(this, f, null)) {
            UniApply c = new UniApply(e, d, this, f);
            push(c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class UniAccept extends UniCompletion {
        Consumer fn;
        UniAccept(Executor executor, CompletableFuture dep,
                  CompletableFuture src, Consumer fn) {
            super(executor, dep, src); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d; CompletableFuture a;
            if ((d = dep) == null ||
                !d.uniAccept(a = src, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; fn = null;
            return d.postFire(a, mode);
        }
    }

    final  boolean uniAccept(CompletableFuture a,
                                Consumer f, UniAccept c) {
        Object r; Throwable x;
        if (a == null || (r = a.result) == null || f == null)
            return false;
        tryComplete: if (result == null) {
            if (r instanceof AltResult) {
                if ((x = ((AltResult)r).ex) != null) {
                    completeThrowable(x, r);
                    break tryComplete;
                }
                r = null;
            }
            try {
                if (c != null && !c.claim())
                    return false;
                @SuppressWarnings("unchecked") S s = (S) r;
                f.accept(s);
                completeNull();
            } catch (Throwable ex) {
                completeThrowable(ex);
            }
        }
        return true;
    }

    private CompletableFuture uniAcceptStage(Executor e,
                                                   Consumer f) {
        if (f == null) throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        if (e != null || !d.uniAccept(this, f, null)) {
            UniAccept c = new UniAccept(e, d, this, f);
            push(c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class UniRun extends UniCompletion {
        Runnable fn;
        UniRun(Executor executor, CompletableFuture dep,
               CompletableFuture src, Runnable fn) {
            super(executor, dep, src); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d; CompletableFuture a;
            if ((d = dep) == null ||
                !d.uniRun(a = src, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; fn = null;
            return d.postFire(a, mode);
        }
    }

    final boolean uniRun(CompletableFuture a, Runnable f, UniRun c) {
        Object r; Throwable x;
        if (a == null || (r = a.result) == null || f == null)
            return false;
        if (result == null) {
            if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
                completeThrowable(x, r);
            else
                try {
                    if (c != null && !c.claim())
                        return false;
                    f.run();
                    completeNull();
                } catch (Throwable ex) {
                    completeThrowable(ex);
                }
        }
        return true;
    }

    private CompletableFuture uniRunStage(Executor e, Runnable f) {
        if (f == null) throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        if (e != null || !d.uniRun(this, f, null)) {
            UniRun c = new UniRun(e, d, this, f);
            push(c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class UniWhenComplete extends UniCompletion {
        BiConsumer fn;
        UniWhenComplete(Executor executor, CompletableFuture dep,
                        CompletableFuture src,
                        BiConsumer fn) {
            super(executor, dep, src); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d; CompletableFuture a;
            if ((d = dep) == null ||
                !d.uniWhenComplete(a = src, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; fn = null;
            return d.postFire(a, mode);
        }
    }

    final boolean uniWhenComplete(CompletableFuture a,
                                  BiConsumer f,
                                  UniWhenComplete c) {
        Object r; T t; Throwable x = null;
        if (a == null || (r = a.result) == null || f == null)
            return false;
        if (result == null) {
            try {
                if (c != null && !c.claim())
                    return false;
                if (r instanceof AltResult) {
                    x = ((AltResult)r).ex;
                    t = null;
                } else {
                    @SuppressWarnings("unchecked") T tr = (T) r;
                    t = tr;
                }
                f.accept(t, x);
                if (x == null) {
                    internalComplete(r);
                    return true;
                }
            } catch (Throwable ex) {
                if (x == null)
                    x = ex;
            }
            completeThrowable(x, r);
        }
        return true;
    }

    private CompletableFuture uniWhenCompleteStage(
        Executor e, BiConsumer f) {
        if (f == null) throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        if (e != null || !d.uniWhenComplete(this, f, null)) {
            UniWhenComplete c = new UniWhenComplete(e, d, this, f);
            push(c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class UniHandle extends UniCompletion {
        BiFunction fn;
        UniHandle(Executor executor, CompletableFuture dep,
                  CompletableFuture src,
                  BiFunction fn) {
            super(executor, dep, src); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d; CompletableFuture a;
            if ((d = dep) == null ||
                !d.uniHandle(a = src, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; fn = null;
            return d.postFire(a, mode);
        }
    }

    final  boolean uniHandle(CompletableFuture a,
                                BiFunction f,
                                UniHandle c) {
        Object r; S s; Throwable x;
        if (a == null || (r = a.result) == null || f == null)
            return false;
        if (result == null) {
            try {
                if (c != null && !c.claim())
                    return false;
                if (r instanceof AltResult) {
                    x = ((AltResult)r).ex;
                    s = null;
                } else {
                    x = null;
                    @SuppressWarnings("unchecked") S ss = (S) r;
                    s = ss;
                }
                completeValue(f.apply(s, x));
            } catch (Throwable ex) {
                completeThrowable(ex);
            }
        }
        return true;
    }

    private  CompletableFuture uniHandleStage(
        Executor e, BiFunction f) {
        if (f == null) throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        if (e != null || !d.uniHandle(this, f, null)) {
            UniHandle c = new UniHandle(e, d, this, f);
            push(c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class UniExceptionally extends UniCompletion {
        Function fn;
        UniExceptionally(CompletableFuture dep, CompletableFuture src,
                         Function fn) {
            super(null, dep, src); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) { // never ASYNC
            // assert mode != ASYNC;
            CompletableFuture d; CompletableFuture a;
            if ((d = dep) == null || !d.uniExceptionally(a = src, fn, this))
                return null;
            dep = null; src = null; fn = null;
            return d.postFire(a, mode);
        }
    }

    final boolean uniExceptionally(CompletableFuture a,
                                   Function f,
                                   UniExceptionally c) {
        Object r; Throwable x;
        if (a == null || (r = a.result) == null || f == null)
            return false;
        if (result == null) {
            try {
                if (r instanceof AltResult && (x = ((AltResult)r).ex) != null) {
                    if (c != null && !c.claim())
                        return false;
                    completeValue(f.apply(x));
                } else
                    internalComplete(r);
            } catch (Throwable ex) {
                completeThrowable(ex);
            }
        }
        return true;
    }

    private CompletableFuture uniExceptionallyStage(
        Function f) {
        if (f == null) throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        if (!d.uniExceptionally(this, f, null)) {
            UniExceptionally c = new UniExceptionally(d, this, f);
            push(c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class UniRelay extends UniCompletion { // for Compose
        UniRelay(CompletableFuture dep, CompletableFuture src) {
            super(null, dep, src);
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d; CompletableFuture a;
            if ((d = dep) == null || !d.uniRelay(a = src))
                return null;
            src = null; dep = null;
            return d.postFire(a, mode);
        }
    }

    final boolean uniRelay(CompletableFuture a) {
        Object r;
        if (a == null || (r = a.result) == null)
            return false;
        if (result == null) // no need to claim
            completeRelay(r);
        return true;
    }

    @SuppressWarnings("serial")
    static final class UniCompose extends UniCompletion {
        Function> fn;
        UniCompose(Executor executor, CompletableFuture dep,
                   CompletableFuture src,
                   Function> fn) {
            super(executor, dep, src); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d; CompletableFuture a;
            if ((d = dep) == null ||
                !d.uniCompose(a = src, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; fn = null;
            return d.postFire(a, mode);
        }
    }

    final  boolean uniCompose(
        CompletableFuture a,
        Function> f,
        UniCompose c) {
        Object r; Throwable x;
        if (a == null || (r = a.result) == null || f == null)
            return false;
        tryComplete: if (result == null) {
            if (r instanceof AltResult) {
                if ((x = ((AltResult)r).ex) != null) {
                    completeThrowable(x, r);
                    break tryComplete;
                }
                r = null;
            }
            try {
                if (c != null && !c.claim())
                    return false;
                @SuppressWarnings("unchecked") S s = (S) r;
                CompletableFuture g = f.apply(s).toCompletableFuture();
                if (g.result == null || !uniRelay(g)) {
                    UniRelay copy = new UniRelay(this, g);
                    g.push(copy);
                    copy.tryFire(SYNC);
                    if (result == null)
                        return false;
                }
            } catch (Throwable ex) {
                completeThrowable(ex);
            }
        }
        return true;
    }

    private  CompletableFuture uniComposeStage(
        Executor e, Function> f) {
        if (f == null) throw new NullPointerException();
        Object r; Throwable x;
        if (e == null && (r = result) != null) {
            // try to return function result directly
            if (r instanceof AltResult) {
                if ((x = ((AltResult)r).ex) != null) {
                    return new CompletableFuture(encodeThrowable(x, r));
                }
                r = null;
            }
            try {
                @SuppressWarnings("unchecked") T t = (T) r;
                CompletableFuture g = f.apply(t).toCompletableFuture();
                Object s = g.result;
                if (s != null)
                    return new CompletableFuture(encodeRelay(s));
                CompletableFuture d = new CompletableFuture();
                UniRelay copy = new UniRelay(d, g);
                g.push(copy);
                copy.tryFire(SYNC);
                return d;
            } catch (Throwable ex) {
                return new CompletableFuture(encodeThrowable(ex));
            }
        }
        CompletableFuture d = new CompletableFuture();
        UniCompose c = new UniCompose(e, d, this, f);
        push(c);
        c.tryFire(SYNC);
        return d;
    }

    /* ------------- Two-input Completions -------------- */

    /** A Completion for an action with two sources */
    @SuppressWarnings("serial")
    abstract static class BiCompletion extends UniCompletion {
        CompletableFuture snd; // second source for action
        BiCompletion(Executor executor, CompletableFuture dep,
                     CompletableFuture src, CompletableFuture snd) {
            super(executor, dep, src); this.snd = snd;
        }
    }

    /** A Completion delegating to a BiCompletion */
    @SuppressWarnings("serial")
    static final class CoCompletion extends Completion {
        BiCompletion base;
        CoCompletion(BiCompletion base) { this.base = base; }
        final CompletableFuture tryFire(int mode) {
            BiCompletion c; CompletableFuture d;
            if ((c = base) == null || (d = c.tryFire(mode)) == null)
                return null;
            base = null; // detach
            return d;
        }
        final boolean isLive() {
            BiCompletion c;
            return (c = base) != null && c.dep != null;
        }
    }

    /** Pushes completion to this and b unless both done. */
    final void bipush(CompletableFuture b, BiCompletion c) {
        if (c != null) {
            Object r;
            while ((r = result) == null && !tryPushStack(c))
                lazySetNext(c, null); // clear on failure
            if (b != null && b != this && b.result == null) {
                Completion q = (r != null) ? c : new CoCompletion(c);
                while (b.result == null && !b.tryPushStack(q))
                    lazySetNext(q, null); // clear on failure
            }
        }
    }

    /** Post-processing after successful BiCompletion tryFire. */
    final CompletableFuture postFire(CompletableFuture a,
                                        CompletableFuture b, int mode) {
        if (b != null && b.stack != null) { // clean second source
            if (mode < 0 || b.result == null)
                b.cleanStack();
            else
                b.postComplete();
        }
        return postFire(a, mode);
    }

    @SuppressWarnings("serial")
    static final class BiApply extends BiCompletion {
        BiFunction fn;
        BiApply(Executor executor, CompletableFuture dep,
                CompletableFuture src, CompletableFuture snd,
                BiFunction fn) {
            super(executor, dep, src, snd); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d;
            CompletableFuture a;
            CompletableFuture b;
            if ((d = dep) == null ||
                !d.biApply(a = src, b = snd, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; snd = null; fn = null;
            return d.postFire(a, b, mode);
        }
    }

    final  boolean biApply(CompletableFuture a,
                                CompletableFuture b,
                                BiFunction f,
                                BiApply c) {
        Object r, s; Throwable x;
        if (a == null || (r = a.result) == null ||
            b == null || (s = b.result) == null || f == null)
            return false;
        tryComplete: if (result == null) {
            if (r instanceof AltResult) {
                if ((x = ((AltResult)r).ex) != null) {
                    completeThrowable(x, r);
                    break tryComplete;
                }
                r = null;
            }
            if (s instanceof AltResult) {
                if ((x = ((AltResult)s).ex) != null) {
                    completeThrowable(x, s);
                    break tryComplete;
                }
                s = null;
            }
            try {
                if (c != null && !c.claim())
                    return false;
                @SuppressWarnings("unchecked") R rr = (R) r;
                @SuppressWarnings("unchecked") S ss = (S) s;
                completeValue(f.apply(rr, ss));
            } catch (Throwable ex) {
                completeThrowable(ex);
            }
        }
        return true;
    }

    private  CompletableFuture biApplyStage(
        Executor e, CompletionStage o,
        BiFunction f) {
        CompletableFuture b;
        if (f == null || (b = o.toCompletableFuture()) == null)
            throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        if (e != null || !d.biApply(this, b, f, null)) {
            BiApply c = new BiApply(e, d, this, b, f);
            bipush(b, c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class BiAccept extends BiCompletion {
        BiConsumer fn;
        BiAccept(Executor executor, CompletableFuture dep,
                 CompletableFuture src, CompletableFuture snd,
                 BiConsumer fn) {
            super(executor, dep, src, snd); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d;
            CompletableFuture a;
            CompletableFuture b;
            if ((d = dep) == null ||
                !d.biAccept(a = src, b = snd, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; snd = null; fn = null;
            return d.postFire(a, b, mode);
        }
    }

    final  boolean biAccept(CompletableFuture a,
                                 CompletableFuture b,
                                 BiConsumer f,
                                 BiAccept c) {
        Object r, s; Throwable x;
        if (a == null || (r = a.result) == null ||
            b == null || (s = b.result) == null || f == null)
            return false;
        tryComplete: if (result == null) {
            if (r instanceof AltResult) {
                if ((x = ((AltResult)r).ex) != null) {
                    completeThrowable(x, r);
                    break tryComplete;
                }
                r = null;
            }
            if (s instanceof AltResult) {
                if ((x = ((AltResult)s).ex) != null) {
                    completeThrowable(x, s);
                    break tryComplete;
                }
                s = null;
            }
            try {
                if (c != null && !c.claim())
                    return false;
                @SuppressWarnings("unchecked") R rr = (R) r;
                @SuppressWarnings("unchecked") S ss = (S) s;
                f.accept(rr, ss);
                completeNull();
            } catch (Throwable ex) {
                completeThrowable(ex);
            }
        }
        return true;
    }

    private  CompletableFuture biAcceptStage(
        Executor e, CompletionStage o,
        BiConsumer f) {
        CompletableFuture b;
        if (f == null || (b = o.toCompletableFuture()) == null)
            throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        if (e != null || !d.biAccept(this, b, f, null)) {
            BiAccept c = new BiAccept(e, d, this, b, f);
            bipush(b, c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class BiRun extends BiCompletion {
        Runnable fn;
        BiRun(Executor executor, CompletableFuture dep,
              CompletableFuture src,
              CompletableFuture snd,
              Runnable fn) {
            super(executor, dep, src, snd); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d;
            CompletableFuture a;
            CompletableFuture b;
            if ((d = dep) == null ||
                !d.biRun(a = src, b = snd, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; snd = null; fn = null;
            return d.postFire(a, b, mode);
        }
    }

    final boolean biRun(CompletableFuture a, CompletableFuture b,
                        Runnable f, BiRun c) {
        Object r, s; Throwable x;
        if (a == null || (r = a.result) == null ||
            b == null || (s = b.result) == null || f == null)
            return false;
        if (result == null) {
            if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
                completeThrowable(x, r);
            else if (s instanceof AltResult && (x = ((AltResult)s).ex) != null)
                completeThrowable(x, s);
            else
                try {
                    if (c != null && !c.claim())
                        return false;
                    f.run();
                    completeNull();
                } catch (Throwable ex) {
                    completeThrowable(ex);
                }
        }
        return true;
    }

    private CompletableFuture biRunStage(Executor e, CompletionStage o,
                                               Runnable f) {
        CompletableFuture b;
        if (f == null || (b = o.toCompletableFuture()) == null)
            throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        if (e != null || !d.biRun(this, b, f, null)) {
            BiRun c = new BiRun<>(e, d, this, b, f);
            bipush(b, c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class BiRelay extends BiCompletion { // for And
        BiRelay(CompletableFuture dep,
                CompletableFuture src,
                CompletableFuture snd) {
            super(null, dep, src, snd);
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d;
            CompletableFuture a;
            CompletableFuture b;
            if ((d = dep) == null || !d.biRelay(a = src, b = snd))
                return null;
            src = null; snd = null; dep = null;
            return d.postFire(a, b, mode);
        }
    }

    boolean biRelay(CompletableFuture a, CompletableFuture b) {
        Object r, s; Throwable x;
        if (a == null || (r = a.result) == null ||
            b == null || (s = b.result) == null)
            return false;
        if (result == null) {
            if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
                completeThrowable(x, r);
            else if (s instanceof AltResult && (x = ((AltResult)s).ex) != null)
                completeThrowable(x, s);
            else
                completeNull();
        }
        return true;
    }

    /** Recursively constructs a tree of completions. */
    static CompletableFuture andTree(CompletableFuture[] cfs,
                                           int lo, int hi) {
        CompletableFuture d = new CompletableFuture();
        if (lo > hi) // empty
            d.result = NIL;
        else {
            CompletableFuture a, b;
            int mid = (lo + hi) >>> 1;
            if ((a = (lo == mid ? cfs[lo] :
                      andTree(cfs, lo, mid))) == null ||
                (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
                      andTree(cfs, mid+1, hi)))  == null)
                throw new NullPointerException();
            if (!d.biRelay(a, b)) {
                BiRelay c = new BiRelay<>(d, a, b);
                a.bipush(b, c);
                c.tryFire(SYNC);
            }
        }
        return d;
    }

    /* ------------- Projected (Ored) BiCompletions -------------- */

    /** Pushes completion to this and b unless either done. */
    final void orpush(CompletableFuture b, BiCompletion c) {
        if (c != null) {
            while ((b == null || b.result == null) && result == null) {
                if (tryPushStack(c)) {
                    if (b != null && b != this && b.result == null) {
                        Completion q = new CoCompletion(c);
                        while (result == null && b.result == null &&
                               !b.tryPushStack(q))
                            lazySetNext(q, null); // clear on failure
                    }
                    break;
                }
                lazySetNext(c, null); // clear on failure
            }
        }
    }

    @SuppressWarnings("serial")
    static final class OrApply extends BiCompletion {
        Function fn;
        OrApply(Executor executor, CompletableFuture dep,
                CompletableFuture src,
                CompletableFuture snd,
                Function fn) {
            super(executor, dep, src, snd); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d;
            CompletableFuture a;
            CompletableFuture b;
            if ((d = dep) == null ||
                !d.orApply(a = src, b = snd, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; snd = null; fn = null;
            return d.postFire(a, b, mode);
        }
    }

    final  boolean orApply(CompletableFuture a,
                                          CompletableFuture b,
                                          Function f,
                                          OrApply c) {
        Object r; Throwable x;
        if (a == null || b == null ||
            ((r = a.result) == null && (r = b.result) == null) || f == null)
            return false;
        tryComplete: if (result == null) {
            try {
                if (c != null && !c.claim())
                    return false;
                if (r instanceof AltResult) {
                    if ((x = ((AltResult)r).ex) != null) {
                        completeThrowable(x, r);
                        break tryComplete;
                    }
                    r = null;
                }
                @SuppressWarnings("unchecked") R rr = (R) r;
                completeValue(f.apply(rr));
            } catch (Throwable ex) {
                completeThrowable(ex);
            }
        }
        return true;
    }

    private  CompletableFuture orApplyStage(
        Executor e, CompletionStage o,
        Function f) {
        CompletableFuture b;
        if (f == null || (b = o.toCompletableFuture()) == null)
            throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        if (e != null || !d.orApply(this, b, f, null)) {
            OrApply c = new OrApply(e, d, this, b, f);
            orpush(b, c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class OrAccept extends BiCompletion {
        Consumer fn;
        OrAccept(Executor executor, CompletableFuture dep,
                 CompletableFuture src,
                 CompletableFuture snd,
                 Consumer fn) {
            super(executor, dep, src, snd); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d;
            CompletableFuture a;
            CompletableFuture b;
            if ((d = dep) == null ||
                !d.orAccept(a = src, b = snd, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; snd = null; fn = null;
            return d.postFire(a, b, mode);
        }
    }

    final  boolean orAccept(CompletableFuture a,
                                           CompletableFuture b,
                                           Consumer f,
                                           OrAccept c) {
        Object r; Throwable x;
        if (a == null || b == null ||
            ((r = a.result) == null && (r = b.result) == null) || f == null)
            return false;
        tryComplete: if (result == null) {
            try {
                if (c != null && !c.claim())
                    return false;
                if (r instanceof AltResult) {
                    if ((x = ((AltResult)r).ex) != null) {
                        completeThrowable(x, r);
                        break tryComplete;
                    }
                    r = null;
                }
                @SuppressWarnings("unchecked") R rr = (R) r;
                f.accept(rr);
                completeNull();
            } catch (Throwable ex) {
                completeThrowable(ex);
            }
        }
        return true;
    }

    private  CompletableFuture orAcceptStage(
        Executor e, CompletionStage o, Consumer f) {
        CompletableFuture b;
        if (f == null || (b = o.toCompletableFuture()) == null)
            throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        if (e != null || !d.orAccept(this, b, f, null)) {
            OrAccept c = new OrAccept(e, d, this, b, f);
            orpush(b, c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class OrRun extends BiCompletion {
        Runnable fn;
        OrRun(Executor executor, CompletableFuture dep,
              CompletableFuture src,
              CompletableFuture snd,
              Runnable fn) {
            super(executor, dep, src, snd); this.fn = fn;
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d;
            CompletableFuture a;
            CompletableFuture b;
            if ((d = dep) == null ||
                !d.orRun(a = src, b = snd, fn, mode > 0 ? null : this))
                return null;
            dep = null; src = null; snd = null; fn = null;
            return d.postFire(a, b, mode);
        }
    }

    final boolean orRun(CompletableFuture a, CompletableFuture b,
                        Runnable f, OrRun c) {
        Object r; Throwable x;
        if (a == null || b == null ||
            ((r = a.result) == null && (r = b.result) == null) || f == null)
            return false;
        if (result == null) {
            try {
                if (c != null && !c.claim())
                    return false;
                if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
                    completeThrowable(x, r);
                else {
                    f.run();
                    completeNull();
                }
            } catch (Throwable ex) {
                completeThrowable(ex);
            }
        }
        return true;
    }

    private CompletableFuture orRunStage(Executor e, CompletionStage o,
                                               Runnable f) {
        CompletableFuture b;
        if (f == null || (b = o.toCompletableFuture()) == null)
            throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        if (e != null || !d.orRun(this, b, f, null)) {
            OrRun c = new OrRun<>(e, d, this, b, f);
            orpush(b, c);
            c.tryFire(SYNC);
        }
        return d;
    }

    @SuppressWarnings("serial")
    static final class OrRelay extends BiCompletion { // for Or
        OrRelay(CompletableFuture dep, CompletableFuture src,
                CompletableFuture snd) {
            super(null, dep, src, snd);
        }
        final CompletableFuture tryFire(int mode) {
            CompletableFuture d;
            CompletableFuture a;
            CompletableFuture b;
            if ((d = dep) == null || !d.orRelay(a = src, b = snd))
                return null;
            src = null; snd = null; dep = null;
            return d.postFire(a, b, mode);
        }
    }

    final boolean orRelay(CompletableFuture a, CompletableFuture b) {
        Object r;
        if (a == null || b == null ||
            ((r = a.result) == null && (r = b.result) == null))
            return false;
        if (result == null)
            completeRelay(r);
        return true;
    }

    /** Recursively constructs a tree of completions. */
    static CompletableFuture orTree(CompletableFuture[] cfs,
                                            int lo, int hi) {
        CompletableFuture d = new CompletableFuture();
        if (lo <= hi) {
            CompletableFuture a, b;
            int mid = (lo + hi) >>> 1;
            if ((a = (lo == mid ? cfs[lo] :
                      orTree(cfs, lo, mid))) == null ||
                (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
                      orTree(cfs, mid+1, hi)))  == null)
                throw new NullPointerException();
            if (!d.orRelay(a, b)) {
                OrRelay c = new OrRelay<>(d, a, b);
                a.orpush(b, c);
                c.tryFire(SYNC);
            }
        }
        return d;
    }

    /* ------------- Zero-input Async forms -------------- */

    @SuppressWarnings("serial")
    static final class AsyncSupply extends ForkJoinTask
            implements Runnable, AsynchronousCompletionTask {
        CompletableFuture dep; Supplier fn;
        AsyncSupply(CompletableFuture dep, Supplier fn) {
            this.dep = dep; this.fn = fn;
        }

        public final Void getRawResult() { return null; }
        public final void setRawResult(Void v) {}
        public final boolean exec() { run(); return true; }

        public void run() {
            CompletableFuture d; Supplier f;
            if ((d = dep) != null && (f = fn) != null) {
                dep = null; fn = null;
                if (d.result == null) {
                    try {
                        d.completeValue(f.get());
                    } catch (Throwable ex) {
                        d.completeThrowable(ex);
                    }
                }
                d.postComplete();
            }
        }
    }

    static  CompletableFuture asyncSupplyStage(Executor e,
                                                     Supplier f) {
        if (f == null) throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        e.execute(new AsyncSupply(d, f));
        return d;
    }

    @SuppressWarnings("serial")
    static final class AsyncRun extends ForkJoinTask
            implements Runnable, AsynchronousCompletionTask {
        CompletableFuture dep; Runnable fn;
        AsyncRun(CompletableFuture dep, Runnable fn) {
            this.dep = dep; this.fn = fn;
        }

        public final Void getRawResult() { return null; }
        public final void setRawResult(Void v) {}
        public final boolean exec() { run(); return true; }

        public void run() {
            CompletableFuture d; Runnable f;
            if ((d = dep) != null && (f = fn) != null) {
                dep = null; fn = null;
                if (d.result == null) {
                    try {
                        f.run();
                        d.completeNull();
                    } catch (Throwable ex) {
                        d.completeThrowable(ex);
                    }
                }
                d.postComplete();
            }
        }
    }

    static CompletableFuture asyncRunStage(Executor e, Runnable f) {
        if (f == null) throw new NullPointerException();
        CompletableFuture d = new CompletableFuture();
        e.execute(new AsyncRun(d, f));
        return d;
    }

    /* ------------- Signallers -------------- */
    @SuppressWarnings("serial")
    static final class Signaller extends Completion
        implements ForkJoinPool.ManagedBlocker {
        long nanos;                    // wait time if timed
        final long deadline;           // non-zero if timed
        volatile int interruptControl; // > 0: interruptible, < 0: interrupted
        volatile Thread thread;

        Signaller(boolean interruptible, long nanos, long deadline) {
            this.thread = Thread.currentThread();
            this.interruptControl = interruptible ? 1 : 0;
            this.nanos = nanos;
            this.deadline = deadline;
        }
        final CompletableFuture tryFire(int ignore) {
            Thread w; // no need to atomically claim
            if ((w = thread) != null) {
                thread = null;
                LockSupport.unpark(w);
            }
            return null;
        }
        public boolean isReleasable() {
            if (thread == null)
                return true;
            if (Thread.interrupted()) {
                int i = interruptControl;
                interruptControl = -1;
                if (i > 0)
                    return true;
            }
            if (deadline != 0L &&
                (nanos <= 0L || (nanos = deadline - System.nanoTime()) <= 0L)) {
                thread = null;
                return true;
            }
            return false;
        }
        public boolean block() {
            if (isReleasable())
                return true;
            else if (deadline == 0L)
                LockSupport.park(this);
            else if (nanos > 0L)
                LockSupport.parkNanos(this, nanos);
            return isReleasable();
        }
        final boolean isLive() { return thread != null; }
    }

    private Object waitingGet(boolean interruptible) {
        Signaller q = null;
        boolean queued = false;
        int spins = -1;
        Object r;
        while ((r = result) == null) {
            if (spins < 0)
                spins = (Runtime.getRuntime().availableProcessors() > 1) ?
                    1 << 8 : 0; // Use brief spin-wait on multiprocessors
            else if (spins > 0) {
                if (ThreadLocalRandom.nextSecondarySeed() >= 0)
                    --spins;
            }
            else if (q == null)
                q = new Signaller(interruptible, 0L, 0L);
            else if (!queued)
                queued = tryPushStack(q);
            else if (interruptible && q.interruptControl < 0) {
                q.thread = null;
                cleanStack();
                return null;
            }
            else if (q.thread != null && result == null) {
                try {
                    ForkJoinPool.managedBlock(q);
                } catch (InterruptedException ie) {
                    q.interruptControl = -1;
                }
            }
        }
        if (q != null) {
            q.thread = null;
            if (q.interruptControl < 0) {
                if (interruptible)
                    r = null; // report interruption
                else
                    Thread.currentThread().interrupt();
            }
        }
        postComplete();
        return r;
    }

    private Object timedGet(long nanos) throws TimeoutException {
        if (Thread.interrupted())
            return null;
        if (nanos <= 0L)
            throw new TimeoutException();
        long d = System.nanoTime() + nanos;
        Signaller q = new Signaller(true, nanos, d == 0L ? 1L : d); // avoid 0
        boolean queued = false;
        Object r;
        // We intentionally don't spin here (as waitingGet does) because
        // the call to nanoTime() above acts much like a spin.
        while ((r = result) == null) {
            if (!queued)
                queued = tryPushStack(q);
            else if (q.interruptControl < 0 || q.nanos <= 0L) {
                q.thread = null;
                cleanStack();
                if (q.interruptControl < 0)
                    return null;
                throw new TimeoutException();
            }
            else if (q.thread != null && result == null) {
                try {
                    ForkJoinPool.managedBlock(q);
                } catch (InterruptedException ie) {
                    q.interruptControl = -1;
                }
            }
        }
        if (q.interruptControl < 0)
            r = null;
        q.thread = null;
        postComplete();
        return r;
    }

    /* ------------- public methods -------------- */
    public CompletableFuture() {
    }

    private CompletableFuture(Object r) {
        this.result = r;
    }

    public static  CompletableFuture supplyAsync(Supplier supplier) {
        return asyncSupplyStage(asyncPool, supplier);
    }

    public static  CompletableFuture supplyAsync(Supplier supplier,
                                                       Executor executor) {
        return asyncSupplyStage(screenExecutor(executor), supplier);
    }

    public static CompletableFuture runAsync(Runnable runnable) {
        return asyncRunStage(asyncPool, runnable);
    }

    public static CompletableFuture runAsync(Runnable runnable,
                                                   Executor executor) {
        return asyncRunStage(screenExecutor(executor), runnable);
    }

    public static  CompletableFuture completedFuture(U value) {
        return new CompletableFuture((value == null) ? NIL : value);
    }

    public boolean isDone() {
        return result != null;
    }

    public T get() throws InterruptedException, ExecutionException {
        Object r;
        return reportGet((r = result) == null ? waitingGet(true) : r);
    }

    public T get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        Object r;
        long nanos = unit.toNanos(timeout);
        return reportGet((r = result) == null ? timedGet(nanos) : r);
    }

    public T join() {
        Object r;
        return reportJoin((r = result) == null ? waitingGet(false) : r);
    }

    public T getNow(T valueIfAbsent) {
        Object r;
        return ((r = result) == null) ? valueIfAbsent : reportJoin(r);
    }

    public boolean complete(T value) {
        boolean triggered = completeValue(value);
        postComplete();
        return triggered;
    }

    public boolean completeExceptionally(Throwable ex) {
        if (ex == null) throw new NullPointerException();
        boolean triggered = internalComplete(new AltResult(ex));
        postComplete();
        return triggered;
    }

    public  CompletableFuture thenApply(
        Function fn) {
        return uniApplyStage(null, fn);
    }

    public  CompletableFuture thenApplyAsync(
        Function fn) {
        return uniApplyStage(asyncPool, fn);
    }

    public  CompletableFuture thenApplyAsync(
        Function fn, Executor executor) {
        return uniApplyStage(screenExecutor(executor), fn);
    }

    public CompletableFuture thenAccept(Consumer action) {
        return uniAcceptStage(null, action);
    }

    public CompletableFuture thenAcceptAsync(Consumer action) {
        return uniAcceptStage(asyncPool, action);
    }

    public CompletableFuture thenAcceptAsync(Consumer action,
                                                   Executor executor) {
        return uniAcceptStage(screenExecutor(executor), action);
    }

    public CompletableFuture thenRun(Runnable action) {
        return uniRunStage(null, action);
    }

    public CompletableFuture thenRunAsync(Runnable action) {
        return uniRunStage(asyncPool, action);
    }

    public CompletableFuture thenRunAsync(Runnable action,
                                                Executor executor) {
        return uniRunStage(screenExecutor(executor), action);
    }

    public  CompletableFuture thenCombine(
        CompletionStage other,
        BiFunction fn) {
        return biApplyStage(null, other, fn);
    }

    public  CompletableFuture thenCombineAsync(
        CompletionStage other,
        BiFunction fn) {
        return biApplyStage(asyncPool, other, fn);
    }

    public  CompletableFuture thenCombineAsync(
        CompletionStage other,
        BiFunction fn, Executor executor) {
        return biApplyStage(screenExecutor(executor), other, fn);
    }

    public  CompletableFuture thenAcceptBoth(
        CompletionStage other,
        BiConsumer action) {
        return biAcceptStage(null, other, action);
    }

    public  CompletableFuture thenAcceptBothAsync(
        CompletionStage other,
        BiConsumer action) {
        return biAcceptStage(asyncPool, other, action);
    }

    public  CompletableFuture thenAcceptBothAsync(
        CompletionStage other,
        BiConsumer action, Executor executor) {
        return biAcceptStage(screenExecutor(executor), other, action);
    }

    public CompletableFuture runAfterBoth(CompletionStage other,
                                                Runnable action) {
        return biRunStage(null, other, action);
    }

    public CompletableFuture runAfterBothAsync(CompletionStage other,
                                                     Runnable action) {
        return biRunStage(asyncPool, other, action);
    }

    public CompletableFuture runAfterBothAsync(CompletionStage other,
                                                     Runnable action,
                                                     Executor executor) {
        return biRunStage(screenExecutor(executor), other, action);
    }

    public  CompletableFuture applyToEither(
        CompletionStage other, Function fn) {
        return orApplyStage(null, other, fn);
    }

    public  CompletableFuture applyToEitherAsync(
        CompletionStage other, Function fn) {
        return orApplyStage(asyncPool, other, fn);
    }

    public  CompletableFuture applyToEitherAsync(
        CompletionStage other, Function fn,
        Executor executor) {
        return orApplyStage(screenExecutor(executor), other, fn);
    }

    public CompletableFuture acceptEither(
        CompletionStage other, Consumer action) {
        return orAcceptStage(null, other, action);
    }

    public CompletableFuture acceptEitherAsync(
        CompletionStage other, Consumer action) {
        return orAcceptStage(asyncPool, other, action);
    }

    public CompletableFuture acceptEitherAsync(
        CompletionStage other, Consumer action,
        Executor executor) {
        return orAcceptStage(screenExecutor(executor), other, action);
    }

    public CompletableFuture runAfterEither(CompletionStage other,
                                                  Runnable action) {
        return orRunStage(null, other, action);
    }

    public CompletableFuture runAfterEitherAsync(CompletionStage other,
                                                       Runnable action) {
        return orRunStage(asyncPool, other, action);
    }

    public CompletableFuture runAfterEitherAsync(CompletionStage other,
                                                       Runnable action,
                                                       Executor executor) {
        return orRunStage(screenExecutor(executor), other, action);
    }

    public  CompletableFuture thenCompose(
        Function> fn) {
        return uniComposeStage(null, fn);
    }

    public  CompletableFuture thenComposeAsync(
        Function> fn) {
        return uniComposeStage(asyncPool, fn);
    }

    public  CompletableFuture thenComposeAsync(
        Function> fn,
        Executor executor) {
        return uniComposeStage(screenExecutor(executor), fn);
    }

    public CompletableFuture whenComplete(
        BiConsumer action) {
        return uniWhenCompleteStage(null, action);
    }

    public CompletableFuture whenCompleteAsync(
        BiConsumer action) {
        return uniWhenCompleteStage(asyncPool, action);
    }

    public CompletableFuture whenCompleteAsync(
        BiConsumer action, Executor executor) {
        return uniWhenCompleteStage(screenExecutor(executor), action);
    }

    public  CompletableFuture handle(
        BiFunction fn) {
        return uniHandleStage(null, fn);
    }

    public  CompletableFuture handleAsync(
        BiFunction fn) {
        return uniHandleStage(asyncPool, fn);
    }

    public  CompletableFuture handleAsync(
        BiFunction fn, Executor executor) {
        return uniHandleStage(screenExecutor(executor), fn);
    }

    public CompletableFuture toCompletableFuture() {
        return this;
    }

    // not in interface CompletionStage
    public CompletableFuture exceptionally(
        Function fn) {
        return uniExceptionallyStage(fn);
    }

    /* ------------- Arbitrary-arity constructions -------------- */
    public static CompletableFuture allOf(CompletableFuture... cfs) {
        return andTree(cfs, 0, cfs.length - 1);
    }

    public static CompletableFuture anyOf(CompletableFuture... cfs) {
        return orTree(cfs, 0, cfs.length - 1);
    }

    /* ------------- Control and status methods -------------- */
    public boolean cancel(boolean mayInterruptIfRunning) {
        boolean cancelled = (result == null) &&
            internalComplete(new AltResult(new CancellationException()));
        postComplete();
        return cancelled || isCancelled();
    }

    public boolean isCancelled() {
        Object r;
        return ((r = result) instanceof AltResult) &&
            (((AltResult)r).ex instanceof CancellationException);
    }

    public boolean isCompletedExceptionally() {
        Object r;
        return ((r = result) instanceof AltResult) && r != NIL;
    }

    public void obtrudeValue(T value) {
        result = (value == null) ? NIL : value;
        postComplete();
    }

    public void obtrudeException(Throwable ex) {
        if (ex == null) throw new NullPointerException();
        result = new AltResult(ex);
        postComplete();
    }

    public int getNumberOfDependents() {
        int count = 0;
        for (Completion p = stack; p != null; p = p.next)
            ++count;
        return count;
    }

    public String toString() {
        Object r = result;
        int count;
        return super.toString() +
            ((r == null) ?
             (((count = getNumberOfDependents()) == 0) ?
              "[Not completed]" :
              "[Not completed, " + count + " dependents]") :
             (((r instanceof AltResult) && ((AltResult)r).ex != null) ?
              "[Completed exceptionally]" :
              "[Completed normally]"));
    }

    // Unsafe mechanics
    private static final sun.misc.Unsafe UNSAFE;
    private static final long RESULT;
    private static final long STACK;
    private static final long NEXT;
    static {
        try {
            final sun.misc.Unsafe u;
            UNSAFE = u = sun.misc.Unsafe.getUnsafe();
            Class k = CompletableFuture.class;
            RESULT = u.objectFieldOffset(k.getDeclaredField("result"));
            STACK = u.objectFieldOffset(k.getDeclaredField("stack"));
            NEXT = u.objectFieldOffset
                (Completion.class.getDeclaredField("next"));
        } catch (Exception x) {
            throw new Error(x);
        }
    }
} 
  

 

Modifier and Type Method and Description
boolean cancel(boolean mayInterruptIfRunning)

尝试取消执行此任务。

V get()

等待计算完成,然后检索其结果。

V get(long timeout, TimeUnit unit)

如果需要等待最多在给定的时间计算完成,然后检索其结果(如果可用)。

boolean isCancelled()

如果此任务在正常完成之前被取消,则返回 true

boolean isDone()

返回 true如果任务已完成。

A Future计算的结果。 提供方法来检查计算是否完成,等待其完成,并检索计算结果。 结果只能在计算完成后使用方法get进行检索,如有必要,阻塞,直到准备就绪。 取消由cancel方法执行。 提供其他方法来确定任务是否正常完成或被取消。 计算完成后,不能取消计算。 如果您想使用Future ,以便不可撤销,但不提供可用的结果,则可以声明Future表格的类型,并返回null作为基础任务的结果。

package java.util.concurrent;

public interface Future {

    boolean cancel(boolean mayInterruptIfRunning);

    boolean isCancelled();

    boolean isDone();

    V get() throws InterruptedException, ExecutionException;

    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

 

Modifier and Type Method and Description
CompletionStage acceptEither(CompletionStage other, Consumer action)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,执行相应的结果作为提供的操作的参数。

CompletionStage acceptEitherAsync(CompletionStage other, Consumer action)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,将使用此阶段的默认异步执行工具执行,其中相应的结果作为提供的操作的参数。

CompletionStage acceptEitherAsync(CompletionStage other, Consumer action, Executor executor)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,将使用提供的执行器执行,其中相应的结果作为参数提供给函数。

CompletionStage applyToEither(CompletionStage other, Function fn)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,执行相应的结果作为提供的函数的参数。

CompletionStage applyToEitherAsync(CompletionStage other, Function fn)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,将使用此阶段的默认异步执行工具执行,其中相应的结果作为提供函数的参数。

CompletionStage applyToEitherAsync(CompletionStage other, Function fn, Executor executor)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,将使用提供的执行器执行,其中相应的结果作为参数提供给函数。

CompletionStage exceptionally(Function fn)

返回一个新的CompletionStage,当此阶段完成异常时,将以此阶段的异常作为提供函数的参数执行。

CompletionStage handle(BiFunction fn)

返回一个新的CompletionStage,当此阶段正常或异常完成时,将使用此阶段的结果和异常作为所提供函数的参数执行。

CompletionStage handleAsync(BiFunction fn)

返回一个新的CompletionStage,当该阶段完成正常或异常时,将使用此阶段的默认异步执行工具执行,此阶段的结果和异常作为提供函数的参数。

CompletionStage handleAsync(BiFunction fn, Executor executor)

返回一个新的CompletionStage,当此阶段完成正常或异常时,将使用提供的执行程序执行此阶段的结果和异常作为提供的函数的参数。

CompletionStage runAfterBoth(CompletionStage other, Runnable action)

返回一个新的CompletionStage,当这个和另一个给定的阶段都正常完成时,执行给定的动作。

CompletionStage runAfterBothAsync(CompletionStage other, Runnable action)

返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,使用此阶段的默认异步执行工具执行给定的操作。

CompletionStage runAfterBothAsync(CompletionStage other, Runnable action, Executor executor)

返回一个新CompletionStage,当这和其他特定阶段正常完成,使用附带的执行见执行给定的动作CompletionStage覆盖特殊的完成规则的文档。

CompletionStage runAfterEither(CompletionStage other, Runnable action)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,执行给定的操作。

CompletionStage runAfterEitherAsync(CompletionStage other, Runnable action)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,使用此阶段的默认异步执行工具执行给定的操作。

CompletionStage runAfterEitherAsync(CompletionStage other, Runnable action, Executor executor)

返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,使用提供的执行器执行给定的操作。

CompletionStage thenAccept(Consumer action)

返回一个新的CompletionStage,当此阶段正常完成时,将以该阶段的结果作为提供的操作的参数执行。

CompletionStage thenAcceptAsync(Consumer action)

返回一个新的CompletionStage,当此阶段正常完成时,将使用此阶段的默认异步执行工具执行,此阶段的结果作为提供的操作的参数。

CompletionStage thenAcceptAsync(Consumer action, Executor executor)

返回一个新的CompletionStage,当此阶段正常完成时,将使用提供的执行程序执行此阶段的结果作为提供的操作的参数。

CompletionStage thenAcceptBoth(CompletionStage other, BiConsumer action)

返回一个新的CompletionStage,当这个和另一个给定的阶段都正常完成时,两个结果作为提供的操作的参数被执行。

CompletionStage thenAcceptBothAsync(CompletionStage other, BiConsumer action)

返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,将使用此阶段的默认异步执行工具执行,其中两个结果作为提供的操作的参数。

CompletionStage thenAcceptBothAsync(CompletionStage other, BiConsumer action, Executor executor)

返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,使用提供的执行器执行,其中两个结果作为提供的函数的参数。

CompletionStage thenApply(Function fn)

返回一个新的CompletionStage,当此阶段正常完成时,将以该阶段的结果作为所提供函数的参数执行。

CompletionStage thenApplyAsync(Function fn)

返回一个新的CompletionStage,当该阶段正常完成时,将使用此阶段的默认异步执行工具执行此阶段的结果作为所提供函数的参数。

CompletionStage thenApplyAsync(Function fn, Executor executor)

返回一个新的CompletionStage,当此阶段正常完成时,将使用提供的执行程序执行此阶段的结果作为提供函数的参数。

CompletionStage thenCombine(CompletionStage other, BiFunction fn)

返回一个新的CompletionStage,当这个和另一个给定的阶段都正常完成时,两个结果作为提供函数的参数执行。

CompletionStage thenCombineAsync(CompletionStage other, BiFunction fn)

返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,将使用此阶段的默认异步执行工具执行,其中两个结果作为提供函数的参数。

CompletionStage thenCombineAsync(CompletionStage other, BiFunction fn, Executor executor)

返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,使用提供的执行器执行,其中两个结果作为提供的函数的参数。

CompletionStage thenCompose(Function> fn)

返回一个新的CompletionStage,当这个阶段正常完成时,这个阶段将作为提供函数的参数执行。

CompletionStage thenComposeAsync(Function> fn)

返回一个新的CompletionStage,当此阶段正常完成时,将使用此阶段的默认异步执行工具执行,此阶段作为提供的函数的参数。

CompletionStage thenComposeAsync(Function> fn, Executor executor)

返回一个新的CompletionStage,当此阶段正常完成时,将使用提供的执行程序执行此阶段的结果作为提供函数的参数。

CompletionStage thenRun(Runnable action)

返回一个新的CompletionStage,当此阶段正常完成时,执行给定的操作。

CompletionStage thenRunAsync(Runnable action)

返回一个新的CompletionStage,当此阶段正常完成时,使用此阶段的默认异步执行工具执行给定的操作。

CompletionStage thenRunAsync(Runnable action, Executor executor)

返回一个新的CompletionStage,当此阶段正常完成时,使用提供的执行程序执行给定的操作。

CompletableFuture toCompletableFuture()

返回一个CompletableFuture,保持与此阶段相同的完成属性。

CompletionStage whenComplete(BiConsumer action)

返回与此阶段相同的结果或异常的新的CompletionStage,当此阶段完成时,将使用结果(或 null如果没有))和此阶段的异常(或 null如果没有))执行给定操作。

CompletionStage whenCompleteAsync(BiConsumer action)

返回一个与此阶段相同结果或异常的新CompletionStage,当此阶段完成时,执行给定操作将使用此阶段的默认异步执行工具执行给定操作,其结果(或 null如果没有))和异常(或 null如果没有)这个阶段作为参数。

CompletionStage whenCompleteAsync(BiConsumer action, Executor executor)

返回与此阶段相同结果或异常的新CompletionStage,当此阶段完成时,使用提供的执行程序执行给定操作,如果没有,则使用结果(或 null如果没有))和异常(或 null如果没有))作为论据。

可能的异步计算的阶段,当另一个完成时间完成时,执行一个动作或计算一个值。 一个阶段在其计算结束时完成,但这又可能触发其他相关阶段。 此界面中定义的功能只需要几种基本形式,从而扩展到更大的方法来捕获一系列使用风格:

所有方法都遵循上述触发,执行和特殊完成规范(在各个方法规范中不重复)。 另外,对于接受它们的方法,用于传递完成结果的参数(也就是对于参数类型为T的T )可能为空,为任何其他参数传递空值将导致抛出NullPointerException

该接口没有定义初始创建方法,强制完成正常或异常的探测完成状态或结果,或等待阶段完成。 CompletionStage的实施可能会提供适当的方式来实现这种效果。 方法toCompletableFuture()通过提供公共转换类型实现了该接口的不同实现之间的互操作性。

阶段执行的计算可以表示为功能,消费者或可运行(分别使用名称包括applyacceptrun的方法),具体取决于是否需要参数和/或生成结果。 例如, stage.thenApply(x -> square(x)).thenAccept(x -> System.out.print(x)).thenRun(() -> System.out.println()) 。 另外一个表单( 组合 )应用阶段本身的功能,而不是它们的结果。

一个阶段的执行可以通过完成一个阶段,或两个阶段的完成,或两个阶段中的任一阶段来触发。 在一个单级的依赖关系使用的是带有前缀方法然后配置。 这些通过两个阶段的结束为契机可以结合自己的成绩和效果,使用相应的命名方法。 由两个阶段中的任一阶段触发的那些不能保证结果或效果中的哪一个用于依赖阶段的计算。

阶段之间的依赖性控制计算的触发,但是否则不保证任何特定的顺序。 此外,新阶段计算的执行可以以三种方式中的任一种进行排列:默认执行,默认异步执行(使用使用阶段的默认异步执行工具的后缀异步方法)或自定义(通过提供的Executor )。 默认和异步模式的执行属性由CompletionStage实现指定,而不是此接口。 具有显式Executor参数的方法可能具有任意执行属性,甚至可能不支持并发执行,而是以适应异步方式进行处理。

两种方法形式支持处理触发阶段是否正常或异常完成:方法whenComplete允许注入动作而不考虑结果,否则保留完成结果。 方法handle还允许阶段计算可以使其他依赖阶段进一步处理的替换结果。 在所有其他情况下,如果一个阶段的计算以(未检查)的异常或错误突然终止,那么所有依赖阶段都要求完成异常, CompletionException将异常作为其原因。 如果一个阶段是依赖于两个两个阶段,都非常完整,那么CompletionException可以对应于这些例外的任何一个。 如果一个阶段依赖于两个其他的任何一个,并且只有一个完成异常,则不能保证依赖阶段是否正常或异常完成。 在方法whenComplete的情况下,当提供的操作本身遇到异常时,如果没有特别地完成,那么该阶段异常地完成该异常。

package java.util.concurrent;
import java.util.function.Supplier;
import java.util.function.Consumer;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.BiFunction;
import java.util.concurrent.Executor;


public interface CompletionStage {

    public  CompletionStage thenApply(Function fn);

    public  CompletionStage thenApplyAsync
        (Function fn);

    public  CompletionStage thenApplyAsync
        (Function fn,
         Executor executor);

    public CompletionStage thenAccept(Consumer action);

    public CompletionStage thenAcceptAsync(Consumer action);

    public CompletionStage thenAcceptAsync(Consumer action,
                                                 Executor executor);

    public CompletionStage thenRun(Runnable action);

    public CompletionStage thenRunAsync(Runnable action);

    public CompletionStage thenRunAsync(Runnable action,
                                              Executor executor);

    public  CompletionStage thenCombine
        (CompletionStage other,
         BiFunction fn);

    public  CompletionStage thenCombineAsync
        (CompletionStage other,
         BiFunction fn);

    public  CompletionStage thenCombineAsync
        (CompletionStage other,
         BiFunction fn,
         Executor executor);

    public  CompletionStage thenAcceptBoth
        (CompletionStage other,
         BiConsumer action);

    public  CompletionStage thenAcceptBothAsync
        (CompletionStage other,
         BiConsumer action);

    public  CompletionStage thenAcceptBothAsync
        (CompletionStage other,
         BiConsumer action,
         Executor executor);

    public CompletionStage runAfterBoth(CompletionStage other,
                                              Runnable action);
   
    public CompletionStage runAfterBothAsync(CompletionStage other,
                                                   Runnable action);

    public CompletionStage runAfterBothAsync(CompletionStage other,
                                                   Runnable action,
                                                   Executor executor);

    public  CompletionStage applyToEither
        (CompletionStage other,
         Function fn);

    public  CompletionStage applyToEitherAsync
        (CompletionStage other,
         Function fn);

    public  CompletionStage applyToEitherAsync
        (CompletionStage other,
         Function fn,
         Executor executor);

    public CompletionStage acceptEither
        (CompletionStage other,
         Consumer action);

    public CompletionStage acceptEitherAsync
        (CompletionStage other,
         Consumer action);

    public CompletionStage acceptEitherAsync
        (CompletionStage other,
         Consumer action,
         Executor executor);

    public CompletionStage runAfterEither(CompletionStage other,
                                                Runnable action);

    public CompletionStage runAfterEitherAsync
        (CompletionStage other,
         Runnable action);

    public CompletionStage runAfterEitherAsync
        (CompletionStage other,
         Runnable action,
         Executor executor);

    public  CompletionStage thenCompose
        (Function> fn);

    public  CompletionStage thenComposeAsync
        (Function> fn);

    public  CompletionStage thenComposeAsync
        (Function> fn,
         Executor executor);

    public CompletionStage exceptionally
        (Function fn);

    public CompletionStage whenComplete
        (BiConsumer action);

    public CompletionStage whenCompleteAsync
        (BiConsumer action);

    public CompletionStage whenCompleteAsync
        (BiConsumer action,
         Executor executor);

    public  CompletionStage handle
        (BiFunction fn);

    public  CompletionStage handleAsync
        (BiFunction fn);

    public  CompletionStage handleAsync
        (BiFunction fn,
         Executor executor);

    public CompletableFuture toCompletableFuture();

}

 

你可能感兴趣的:(Java源码)