java8.util.concurrent.CompletableFuture Maven / Gradle / Ivy
Show all versions of streamsupport-cfuture Show documentation
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java8.util.concurrent;
import java8.util.Objects;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.LockSupport;
import java8.util.function.BiConsumer;
import java8.util.function.BiFunction;
import java8.util.function.Consumer;
import java8.util.function.Function;
import java8.util.function.Supplier;
/**
* 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.
*
* When two or more threads attempt to
* {@link #complete complete},
* {@link #completeExceptionally completeExceptionally}, or
* {@link #cancel cancel}
* a CompletableFuture, only one of them succeeds.
*
*
In addition to these and related methods for directly
* manipulating status and results, CompletableFuture implements
* interface {@link CompletionStage} with the following policies:
*
* - Actions supplied for dependent completions of
* non-async methods may be performed by the thread that
* completes the current CompletableFuture, or by any other caller of
* a completion method.
*
*
- All async 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.
*
*
- 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.
*
*
- 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}.
*
*
* CompletableFuture also implements {@link Future} with the following
* policies:
*
* - 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.
*
*
- 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.
*
*
* 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.
*
*
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:
*
*
{@code
* class MyCompletableFuture extends CompletableFuture {
* static final Executor myExecutor = ...;
* public MyCompletableFuture() { }
* public CompletableFuture newIncompleteFuture() {
* return new MyCompletableFuture(); }
* public Executor defaultExecutor() {
* return myExecutor; }
* public void obtrudeValue(T value) {
* throw new UnsupportedOperationException(); }
* public void obtrudeException(Throwable ex) {
* throw new UnsupportedOperationException(); }
* }}
*
* @author Doug Lea
* @param The result type returned by this future's {@code join}
* and {@code get} methods
* @since 1.8
*/
public class CompletableFuture implements Future, CompletionStage {
// CVS rev. 1.212
/*
* Overview:
*
* A CompletableFuture may have dependent completion actions,
* collected in a linked stack. It atomically completes by CASing
* a result field, and then pops off and runs those actions. This
* applies across normal vs exceptional outcomes, sync vs async
* actions, binary triggers, and various forms of completions.
*
* Non-nullness of volatile field "result" indicates done. It may
* be set directly if known to be thread-confined, else via CAS.
* An AltResult is used to box null as a result, as well as to
* hold exceptions. Using a single field makes completion simple
* to detect and trigger. Result encoding and decoding is
* straightforward but tedious and adds to the sprawl of trapping
* and associating exceptions with targets. Minor simplifications
* rely on (static) NIL (to box null results) being the only
* AltResult with a null exception field, so we don't usually need
* explicit comparisons. Even though some of the generics casts
* are unchecked (see SuppressWarnings annotations), they are
* placed to be appropriate even if checked.
*
* Dependent actions are represented by Completion objects linked
* as Treiber stacks headed by field "stack". There are Completion
* classes for each kind of action, grouped into:
* - single-input (UniCompletion),
* - two-input (BiCompletion),
* - projected (BiCompletions using exactly one of two inputs),
* - shared (CoCompletion, used by the second of two sources),
* - zero-input source actions,
* - Signallers that unblock waiters.
* Class Completion extends ForkJoinTask to enable async execution
* (adding no space overhead because we exploit its "tag" methods
* to maintain claims). It is also declared as Runnable to allow
* usage with arbitrary executors.
*
* Support for each kind of CompletionStage relies on a separate
* class, along with two CompletableFuture methods:
*
* * A Completion class with name X corresponding to function,
* prefaced with "Uni", "Bi", or "Or". Each class contains
* fields for source(s), actions, and dependent. They are
* boringly similar, differing from others only with respect to
* underlying functional forms. We do this so that users don't
* encounter layers of adapters in common usages.
*
* * Boolean CompletableFuture method x(...) (for example
* biApply) takes all of the arguments needed to check that an
* action is triggerable, and then either runs the action or
* arranges its async execution by executing its Completion
* argument, if present. The method returns true if known to be
* complete.
*
* * Completion method tryFire(int mode) invokes the associated x
* method with its held arguments, and on success cleans up.
* The mode argument allows tryFire to be called twice (SYNC,
* then ASYNC); the first to screen and trap exceptions while
* arranging to execute, and the second when called from a task.
* (A few classes are not used async so take slightly different
* forms.) The claim() callback suppresses function invocation
* if already claimed by another thread.
*
* * Some classes (for example UniApply) have separate handling
* code for when known to be thread-confined ("now" methods) and
* for when shared (in tryFire), for efficiency.
*
* * CompletableFuture method xStage(...) is called from a public
* stage method of CompletableFuture f. It screens user
* arguments and invokes and/or creates the stage object. If
* not async and already triggerable, the action is run
* immediately. Otherwise a Completion c is created, and
* submitted to the executor if triggerable, or pushed onto f's
* stack if not. Completion actions are started via c.tryFire.
* We recheck after pushing to a source future's stack to cover
* possible races if the source completes while pushing.
* Classes with two inputs (for example BiApply) deal with races
* across both while pushing actions. The second completion is
* a CoCompletion pointing to the first, shared so that at most
* one performs the action. The multiple-arity methods allOf
* does this pairwise to form trees of completions. Method
* anyOf is handled differently from allOf because completion of
* any source should trigger a cleanStack of other sources.
* Each AnyOf completion can reach others via a shared array.
*
* Note that the generic type parameters of methods vary according
* to whether "this" is a source, dependent, or completion.
*
* Method postComplete is called upon completion unless the target
* is guaranteed not to be observable (i.e., not yet returned or
* linked). Multiple threads can call postComplete, which
* atomically pops each dependent action, and tries to trigger it
* via method tryFire, in NESTED mode. Triggering can propagate
* recursively, so NESTED mode returns its completed dependent (if
* one exists) for further processing by its caller (see method
* postFire).
*
* Blocking methods get() and join() rely on Signaller Completions
* that wake up waiting threads. The mechanics are similar to
* Treiber stack wait-nodes used in FutureTask, Phaser, and
* SynchronousQueue. See their internal documentation for
* algorithmic details.
*
* Without precautions, CompletableFutures would be prone to
* garbage accumulation as chains of Completions build up, each
* pointing back to its sources. So we null out fields as soon as
* possible. The screening checks needed anyway harmlessly ignore
* null arguments that may have been obtained during races with
* threads nulling out fields. We also try to unlink non-isLive
* (fired or cancelled) Completions from stacks that might
* otherwise never be popped: Method cleanStack always unlinks non
* isLive completions from the head of stack; others may
* occasionally remain if racing with other cancellations or
* removals.
*
* Completion fields need not be declared as final or volatile
* because they are only visible to other threads upon safe
* publication.
*/
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 U.compareAndSwapObject(this, RESULT, null, r);
}
final boolean casStack(Completion cmp, Completion val) {
return U.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 U.compareAndSwapObject(this, STACK, h, c);
}
/** Unconditionally pushes c onto stack, retrying if necessary. */
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 U.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 U.compareAndSwapObject(this, RESULT, null,
(t == null) ? NIL : t);
}
/**
* Returns the encoding of the given (non-null) exception as a
* wrapped CompletionException unless it is one already.
*/
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 U.compareAndSwapObject(this, RESULT, null,
encodeThrowable(x));
}
/**
* Returns the encoding of the given (non-null) exception as a
* wrapped CompletionException unless it is one already. May
* return the given Object r (which must have been the result of a
* source future) if it is equivalent, i.e. if this is a simple
* relay of an existing CompletionException.
*/
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);
}
/**
* Completes with the given (non-null) exceptional result as a
* wrapped CompletionException unless it is one already, unless
* already completed. May complete with the given Object r
* (which must have been the result of a source future) if it is
* equivalent, i.e. if this is a simple propagation of an
* existing CompletionException.
*/
final boolean completeThrowable(Throwable x, Object r) {
return U.compareAndSwapObject(this, RESULT, null,
encodeThrowable(x, r));
}
/**
* Returns the encoding of the given arguments: if the exception
* is non-null, encodes as AltResult. Otherwise uses the given
* value, boxed as NIL if null.
*/
Object encodeOutcome(T t, Throwable x) {
return (x == null) ? (t == null) ? NIL : t : encodeThrowable(x);
}
/**
* Returns the encoding of a copied outcome; if exceptional,
* rewraps as a CompletionException, else returns argument.
*/
static Object encodeRelay(Object r) {
Throwable x;
if (r instanceof AltResult
&& (x = ((AltResult)r).ex) != null
&& !(x instanceof CompletionException))
r = new AltResult(new CompletionException(x));
return r;
}
/**
* Completes with r or a copy of r, unless already completed.
* If exceptional, r is first coerced to a CompletionException.
*/
final boolean completeRelay(Object r) {
return U.compareAndSwapObject(this, RESULT, null,
encodeRelay(r));
}
/**
* Reports result using Future.get conventions.
*/
private static Object 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);
}
return r;
}
/**
* Decodes outcome to return result or throw unchecked exception.
*/
private static Object 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);
}
return r;
}
/* ------------- Async task preliminaries -------------- */
/**
* A marker interface identifying asynchronous tasks produced by
* {@code async} methods. This may be useful for monitoring,
* debugging, and tracking asynchronous activities.
*
* @since 1.8
*/
public static interface AsynchronousCompletionTask {
}
private static final boolean USE_COMMON_POOL =
(ForkJoinPool.getCommonPoolParallelism() > 1);
/**
* Default executor -- ForkJoinPool.commonPool() unless it cannot
* support parallelism.
*/
private static final Executor ASYNC_POOL = USE_COMMON_POOL ?
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(); }
}
/**
* Null-checks user executor argument, and translates uses of
* commonPool to ASYNC_POOL in case parallelism disabled.
*/
static Executor screenExecutor(Executor e) {
if (!USE_COMMON_POOL && e == ForkJoinPool.commonPool())
return ASYNC_POOL;
return Objects.requireNonNull(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
/**
* Performs completion action if triggered, returning a
* dependent that may need propagation, if one exists.
*
* @param mode SYNC, ASYNC, or NESTED
*/
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 false; }
public final Void getRawResult() { return null; }
public final void setRawResult(Void v) {}
}
static void lazySetNext(Completion c, Completion next) {
U.putOrderedObject(c, NEXT, next);
}
static boolean casNext(Completion c, Completion cmp, Completion val) {
return U.compareAndSwapObject(c, NEXT, cmp, val);
}
/**
* Pops and tries to trigger all reachable dependents. Call only
* when known to be done.
*/
final void postComplete() {
/*
* On each step, variable f holds current dependents to pop
* and run. It is extended along only one path at a time,
* pushing others to avoid unbounded recursion.
*/
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;
}
casNext(h, t, null); // try to detach
}
f = (d = h.tryFire(NESTED)) == null ? this : d;
}
}
}
/** Traverses stack and unlinks one or more dead Completions, if found. */
final void cleanStack() {
boolean unlinked = false;
Completion p;
while ((p = stack) != null && !p.isLive()) // ensure head of stack live
unlinked = casStack(p, p.next);
if (p != null && !unlinked) { // try to unlink first nonlive
for (Completion q = p.next; q != null;) {
Completion s = q.next;
if (q.isLive()) {
p = q;
q = s;
}
else {
casNext(p, q, s);
break;
}
}
}
}
/* ------------- 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;
}
/**
* Returns true if action can be run. Call only when known to
* be triggerable. Uses FJ tag bit to ensure that only one
* thread claims ownership. If async, starts as task -- a
* later call to tryFire will run action.
*/
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 unless it completes while trying.
* Caller should first check that result is null.
*/
final void unipush(Completion c) {
if (c != null) {
while (!tryPushStack(c)) {
if (result != null) {
lazySetNext(c, null);
break;
}
}
if (result != null)
c.tryFire(SYNC);
}
}
/**
* Post-processing by dependent after successful UniCompletion tryFire.
* Tries to clean stack of source a, and then either runs postComplete
* or returns this to caller, depending on mode.
*/
final CompletableFuture postFire(CompletableFuture> a, int mode) {
if (a != null && a.stack != null) {
Object r;
if ((r = a.result) == null)
a.cleanStack();
if (mode >= 0 && (r != null || a.result != null))
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 super T,? extends V> fn;
UniApply(Executor executor, CompletableFuture dep,
CompletableFuture src,
Function super T,? extends V> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture tryFire(int mode) {
CompletableFuture d; CompletableFuture a;
Object r; Throwable x; Function super T,? extends V> f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (r = a.result) == null)
return null;
tryComplete: if (d.result == null) {
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.completeThrowable(x, r);
break tryComplete;
}
r = null;
}
try {
if (mode <= 0 && !claim())
return null;
else {
@SuppressWarnings("unchecked") T t = (T) r;
d.completeValue(f.apply(t));
}
} catch (Throwable ex) {
d.completeThrowable(ex);
}
}
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
private CompletableFuture uniApplyStage(
Executor e, Function super T,? extends V> f) {
Objects.requireNonNull(f);
Object r;
if ((r = result) != null)
return uniApplyNow(r, e, f);
CompletableFuture d = newIncompleteFuture();
unipush(new UniApply(e, d, this, f));
return d;
}
private CompletableFuture uniApplyNow(
Object r, Executor e, Function super T,? extends V> f) {
Throwable x;
CompletableFuture d = newIncompleteFuture();
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.result = encodeThrowable(x, r);
return d;
}
r = null;
}
try {
if (e != null) {
e.execute(new UniApply(null, d, this, f));
} else {
@SuppressWarnings("unchecked") T t = (T) r;
d.result = d.encodeValue(f.apply(t));
}
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
return d;
}
@SuppressWarnings("serial")
static final class UniAccept extends UniCompletion {
Consumer super T> fn;
UniAccept(Executor executor, CompletableFuture dep,
CompletableFuture src, Consumer super T> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture tryFire(int mode) {
CompletableFuture d; CompletableFuture a;
Object r; Throwable x; Consumer super T> f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (r = a.result) == null)
return null;
tryComplete: if (d.result == null) {
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.completeThrowable(x, r);
break tryComplete;
}
r = null;
}
try {
if (mode <= 0 && !claim())
return null;
else {
@SuppressWarnings("unchecked") T t = (T) r;
f.accept(t);
d.completeNull();
}
} catch (Throwable ex) {
d.completeThrowable(ex);
}
}
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
private CompletableFuture uniAcceptStage(Executor e,
Consumer super T> f) {
Objects.requireNonNull(f);
Object r;
if ((r = result) != null)
return uniAcceptNow(r, e, f);
CompletableFuture d = newIncompleteFuture();
unipush(new UniAccept(e, d, this, f));
return d;
}
private CompletableFuture uniAcceptNow(
Object r, Executor e, Consumer super T> f) {
Throwable x;
CompletableFuture d = newIncompleteFuture();
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.result = encodeThrowable(x, r);
return d;
}
r = null;
}
try {
if (e != null) {
e.execute(new UniAccept(null, d, this, f));
} else {
@SuppressWarnings("unchecked") T t = (T) r;
f.accept(t);
d.result = NIL;
}
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
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;
Object r; Throwable x; Runnable f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (r = a.result) == null)
return null;
if (d.result == null) {
if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
d.completeThrowable(x, r);
else
try {
if (mode <= 0 && !claim())
return null;
else {
f.run();
d.completeNull();
}
} catch (Throwable ex) {
d.completeThrowable(ex);
}
}
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
private CompletableFuture uniRunStage(Executor e, Runnable f) {
Objects.requireNonNull(f);
Object r;
if ((r = result) != null)
return uniRunNow(r, e, f);
CompletableFuture d = newIncompleteFuture();
unipush(new UniRun(e, d, this, f));
return d;
}
private CompletableFuture uniRunNow(Object r, Executor e, Runnable f) {
Throwable x;
CompletableFuture d = newIncompleteFuture();
if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
d.result = encodeThrowable(x, r);
else
try {
if (e != null) {
e.execute(new UniRun(null, d, this, f));
} else {
f.run();
d.result = NIL;
}
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
return d;
}
@SuppressWarnings("serial")
static final class UniWhenComplete extends UniCompletion {
BiConsumer super T, ? super Throwable> fn;
UniWhenComplete(Executor executor, CompletableFuture dep,
CompletableFuture src,
BiConsumer super T, ? super Throwable> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture tryFire(int mode) {
CompletableFuture d; CompletableFuture a;
Object r; BiConsumer super T, ? super Throwable> f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (r = a.result) == null
|| !d.uniWhenComplete(r, f, mode > 0 ? null : this))
return null;
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
final boolean uniWhenComplete(Object r,
BiConsumer super T, ? super Throwable> f, UniWhenComplete c) {
T t;
Throwable x = null;
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;
}// else if (x != ex) {
// x.addSuppressed(ex); // XXX
// }
}
completeThrowable(x, r);
}
return true;
}
private CompletableFuture uniWhenCompleteStage(
Executor e, BiConsumer super T, ? super Throwable> f) {
Objects.requireNonNull(f);
CompletableFuture d = newIncompleteFuture();
Object r;
if ((r = result) == null)
unipush(new UniWhenComplete(e, d, this, f));
else if (e == null)
d.uniWhenComplete(r, f, null);
else {
try {
e.execute(new UniWhenComplete(null, d, this, f));
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
}
return d;
}
@SuppressWarnings("serial")
static final class UniHandle extends UniCompletion {
BiFunction super T, Throwable, ? extends V> fn;
UniHandle(Executor executor, CompletableFuture dep,
CompletableFuture src,
BiFunction super T, Throwable, ? extends V> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture tryFire(int mode) {
CompletableFuture d; CompletableFuture a;
Object r; BiFunction super T, Throwable, ? extends V> f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (r = a.result) == null
|| !d.uniHandle(r, f, mode > 0 ? null : this))
return null;
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
final boolean uniHandle(Object r,
BiFunction super S, Throwable, ? extends T> f, UniHandle c) {
S s;
Throwable x;
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 super T, Throwable, ? extends V> f) {
Objects.requireNonNull(f);
CompletableFuture d = newIncompleteFuture();
Object r;
if ((r = result) == null)
unipush(new UniHandle(e, d, this, f));
else if (e == null)
d.uniHandle(r, f, null);
else {
try {
e.execute(new UniHandle(null, d, this, f));
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
}
return d;
}
@SuppressWarnings("serial")
static final class UniExceptionally extends UniCompletion {
Function super Throwable, ? extends T> fn;
UniExceptionally(CompletableFuture dep, CompletableFuture src,
Function super Throwable, ? extends T> fn) {
super(null, dep, src); this.fn = fn;
}
final CompletableFuture tryFire(int mode) { // never ASYNC
// assert mode != ASYNC;
CompletableFuture d; CompletableFuture a;
Object r; Function super Throwable, ? extends T> f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (r = a.result) == null
|| !d.uniExceptionally(r, f, this))
return null;
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
final boolean uniExceptionally(Object r,
Function super Throwable, ? extends T> f, UniExceptionally c) {
Throwable x;
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) {
Objects.requireNonNull(f);
CompletableFuture d = newIncompleteFuture();
Object r;
if ((r = result) == null)
unipush(new UniExceptionally(d, this, f));
else
d.uniExceptionally(r, f, null);
return d;
}
@SuppressWarnings("serial")
static final class UniRelay extends UniCompletion {
UniRelay(CompletableFuture dep, CompletableFuture src) {
super(null, dep, src);
}
final CompletableFuture tryFire(int mode) {
CompletableFuture d; CompletableFuture a; Object r;
if ((d = dep) == null
|| (a = src) == null || (r = a.result) == null)
return null;
if (d.result == null)
d.completeRelay(r);
src = null; dep = null;
return d.postFire(a, mode);
}
}
private static CompletableFuture uniCopyStage(
CompletableFuture src) {
Object r;
CompletableFuture d = src.newIncompleteFuture();
if ((r = src.result) != null)
d.result = encodeRelay(r);
else
src.unipush(new UniRelay(d, src));
return d;
}
private MinimalStage uniAsMinimalStage() {
Object r;
if ((r = result) != null)
return new MinimalStage(encodeRelay(r));
MinimalStage d = new MinimalStage();
unipush(new UniRelay(d, this));
return d;
}
@SuppressWarnings("serial")
static final class UniCompose extends UniCompletion {
Function super T, ? extends CompletionStage> fn;
UniCompose(Executor executor, CompletableFuture dep,
CompletableFuture src,
Function super T, ? extends CompletionStage> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture tryFire(int mode) {
CompletableFuture d; CompletableFuture a;
Function super T, ? extends CompletionStage> f;
Object r; Throwable x;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (r = a.result) == null)
return null;
tryComplete: if (d.result == null) {
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.completeThrowable(x, r);
break tryComplete;
}
r = null;
}
try {
if (mode <= 0 && !claim())
return null;
@SuppressWarnings("unchecked") T t = (T) r;
CompletableFuture g = f.apply(t).toCompletableFuture();
if ((r = g.result) != null)
d.completeRelay(r);
else {
g.unipush(new UniRelay(d, g));
if (d.result == null)
return null;
}
} catch (Throwable ex) {
d.completeThrowable(ex);
}
}
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
private CompletableFuture uniComposeStage(
Executor e, Function super T, ? extends CompletionStage> f) {
Objects.requireNonNull(f);
CompletableFuture d = newIncompleteFuture();
Object r, s; Throwable x;
if ((r = result) == null)
unipush(new UniCompose(e, d, this, f));
else if (e == null) {
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.result = encodeThrowable(x, r);
return d;
}
r = null;
}
try {
@SuppressWarnings("unchecked") T t = (T) r;
CompletableFuture g = f.apply(t).toCompletableFuture();
if ((s = g.result) != null)
d.result = encodeRelay(s);
else {
g.unipush(new UniRelay(d, g));
}
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
}
else
try {
e.execute(new UniCompose(null, d, this, f));
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
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.isLive()
&& c.dep != null;
}
}
/**
* Pushes completion to this and b unless both done.
* Caller should first check that either result or b.result is null.
*/
final void bipush(CompletableFuture> b, BiCompletion,?,?> c) {
if (c != null) {
while (result == null) {
if (tryPushStack(c)) {
if (b.result == null)
b.unipush(new CoCompletion(c));
else if (result != null)
c.tryFire(SYNC);
return;
}
}
b.unipush(c);
}
}
/** Post-processing after successful BiCompletion tryFire. */
final CompletableFuture postFire(CompletableFuture> a,
CompletableFuture> b, int mode) {
if (b != null && b.stack != null) { // clean second source
Object r;
if ((r = b.result) == null)
b.cleanStack();
if (mode >= 0 && (r != null || b.result != null))
b.postComplete();
}
return postFire(a, mode);
}
@SuppressWarnings("serial")
static final class BiApply extends BiCompletion {
BiFunction super T,? super U,? extends V> fn;
BiApply(Executor executor, CompletableFuture dep,
CompletableFuture src, CompletableFuture snd,
BiFunction super T,? super U,? extends V> fn) {
super(executor, dep, src, snd); this.fn = fn;
}
final CompletableFuture tryFire(int mode) {
CompletableFuture d;
CompletableFuture a;
CompletableFuture b;
Object r, s; BiFunction super T,? super U,? extends V> f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (r = a.result) == null
|| (b = snd) == null || (s = b.result) == null
|| !d.biApply(r, s, f, mode > 0 ? null : this))
return null;
dep = null; src = null; snd = null; fn = null;
return d.postFire(a, b, mode);
}
}
final boolean biApply(Object r, Object s,
BiFunction super R, ? super S, ? extends T> f, BiApply c) {
Throwable x;
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 super T,? super U,? extends V> f) {
CompletableFuture b; Object r, s;
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
CompletableFuture d = newIncompleteFuture();
if ((r = result) == null || (s = b.result) == null)
bipush(b, new BiApply(e, d, this, b, f));
else if (e == null)
d.biApply(r, s, f, null);
else
try {
e.execute(new BiApply(null, d, this, b, f));
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
return d;
}
@SuppressWarnings("serial")
static final class BiAccept extends BiCompletion {
BiConsumer super T,? super U> fn;
BiAccept(Executor executor, CompletableFuture dep,
CompletableFuture src, CompletableFuture snd,
BiConsumer super T,? super U> fn) {
super(executor, dep, src, snd); this.fn = fn;
}
final CompletableFuture tryFire(int mode) {
CompletableFuture d;
CompletableFuture a;
CompletableFuture b;
Object r, s; BiConsumer super T,? super U> f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (r = a.result) == null
|| (b = snd) == null || (s = b.result) == null
|| !d.biAccept(r, s, f, mode > 0 ? null : this))
return null;
dep = null; src = null; snd = null; fn = null;
return d.postFire(a, b, mode);
}
}
final boolean biAccept(Object r, Object s,
BiConsumer super R, ? super S> f, BiAccept c) {
Throwable x;
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 super T,? super U> f) {
CompletableFuture b; Object r, s;
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
CompletableFuture d = newIncompleteFuture();
if ((r = result) == null || (s = b.result) == null)
bipush(b, new BiAccept(e, d, this, b, f));
else if (e == null)
d.biAccept(r, s, f, null);
else
try {
e.execute(new BiAccept(null, d, this, b, f));
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
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;
Object r, s; Runnable f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (r = a.result) == null
|| (b = snd) == null || (s = b.result) == null
|| !d.biRun(r, s, f, mode > 0 ? null : this))
return null;
dep = null; src = null; snd = null; fn = null;
return d.postFire(a, b, mode);
}
}
final boolean biRun(Object r, Object s, Runnable f, BiRun,?> c) {
Throwable x; Object z;
if (result == null) {
if ((r instanceof AltResult
&& (x = ((AltResult)(z = r)).ex) != null) ||
(s instanceof AltResult
&& (x = ((AltResult)(z = s)).ex) != null))
completeThrowable(x, z);
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;
Object r, s;
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
CompletableFuture d = newIncompleteFuture();
if ((r = result) == null || (s = b.result) == null)
bipush(b, new BiRun(e, d, this, b, f));
else if (e == null)
d.biRun(r, s, f, null);
else
try {
e.execute(new BiRun(null, d, this, b, f));
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
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;
Object r, s, z; Throwable x;
if ((d = dep) == null
|| (a = src) == null || (r = a.result) == null
|| (b = snd) == null || (s = b.result) == null)
return null;
if (d.result == null) {
if ((r instanceof AltResult
&& (x = ((AltResult)(z = r)).ex) != null) ||
(s instanceof AltResult
&& (x = ((AltResult)(z = s)).ex) != null))
d.completeThrowable(x, z);
else
d.completeNull();
}
src = null; snd = null; dep = null;
return d.postFire(a, b, mode);
}
}
/** 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; Object r, s, z; Throwable x;
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 ((r = a.result) == null || (s = b.result) == null)
a.bipush(b, new BiRelay(d, a, b));
else if ((r instanceof AltResult
&& (x = ((AltResult)(z = r)).ex) != null) ||
(s instanceof AltResult
&& (x = ((AltResult)(z = s)).ex) != null))
d.result = encodeThrowable(x, z);
else
d.result = NIL;
}
return d;
}
/* ------------- Projected (Ored) BiCompletions -------------- */
/**
* Pushes completion to this and b unless either done.
* Caller should first check that result and b.result are both null.
*/
final void orpush(CompletableFuture> b, BiCompletion,?,?> c) {
if (c != null) {
while (!tryPushStack(c)) {
if (result != null) {
lazySetNext(c, null);
break;
}
}
if (result != null)
c.tryFire(SYNC);
else
b.unipush(new CoCompletion(c));
}
}
@SuppressWarnings("serial")
static final class OrApply extends BiCompletion {
Function super T,? extends V> fn;
OrApply(Executor executor, CompletableFuture dep,
CompletableFuture src, CompletableFuture snd,
Function super T,? extends V> fn) {
super(executor, dep, src, snd); this.fn = fn;
}
final CompletableFuture tryFire(int mode) {
CompletableFuture d;
CompletableFuture a;
CompletableFuture b;
Object r; Throwable x; Function super T,? extends V> f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (b = snd) == null
|| ((r = a.result) == null && (r = b.result) == null))
return null;
tryComplete: if (d.result == null) {
try {
if (mode <= 0 && !claim())
return null;
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.completeThrowable(x, r);
break tryComplete;
}
r = null;
}
@SuppressWarnings("unchecked") T t = (T) r;
d.completeValue(f.apply(t));
} catch (Throwable ex) {
d.completeThrowable(ex);
}
}
dep = null; src = null; snd = null; fn = null;
return d.postFire(a, b, mode);
}
}
private CompletableFuture orApplyStage(
Executor e, CompletionStage o, Function super T, ? extends V> f) {
CompletableFuture b;
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
Object r; CompletableFuture extends T> z;
if ((r = (z = this).result) != null ||
(r = (z = b).result) != null)
return z.uniApplyNow(r, e, f);
CompletableFuture d = newIncompleteFuture();
orpush(b, new OrApply(e, d, this, b, f));
return d;
}
@SuppressWarnings("serial")
static final class OrAccept extends BiCompletion {
Consumer super T> fn;
OrAccept(Executor executor, CompletableFuture dep,
CompletableFuture src, CompletableFuture snd,
Consumer super T> fn) {
super(executor, dep, src, snd); this.fn = fn;
}
final CompletableFuture tryFire(int mode) {
CompletableFuture d;
CompletableFuture a;
CompletableFuture b;
Object r; Throwable x; Consumer super T> f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (b = snd) == null
|| ((r = a.result) == null && (r = b.result) == null))
return null;
tryComplete: if (d.result == null) {
try {
if (mode <= 0 && !claim())
return null;
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.completeThrowable(x, r);
break tryComplete;
}
r = null;
}
@SuppressWarnings("unchecked") T t = (T) r;
f.accept(t);
d.completeNull();
} catch (Throwable ex) {
d.completeThrowable(ex);
}
}
dep = null; src = null; snd = null; fn = null;
return d.postFire(a, b, mode);
}
}
private CompletableFuture orAcceptStage(
Executor e, CompletionStage o, Consumer super T> f) {
CompletableFuture b;
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
Object r; CompletableFuture extends T> z;
if ((r = (z = this).result) != null ||
(r = (z = b).result) != null)
return z.uniAcceptNow(r, e, f);
CompletableFuture d = newIncompleteFuture();
orpush(b, new OrAccept(e, d, this, b, f));
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;
Object r; Throwable x; Runnable f;
if ((d = dep) == null || (f = fn) == null
|| (a = src) == null || (b = snd) == null
|| ((r = a.result) == null && (r = b.result) == null))
return null;
if (d.result == null) {
try {
if (mode <= 0 && !claim())
return null;
else if (r instanceof AltResult
&& (x = ((AltResult)r).ex) != null)
d.completeThrowable(x, r);
else {
f.run();
d.completeNull();
}
} catch (Throwable ex) {
d.completeThrowable(ex);
}
}
dep = null; src = null; snd = null; fn = null;
return d.postFire(a, b, mode);
}
}
private CompletableFuture orRunStage(Executor e,
CompletionStage> o, Runnable f) {
CompletableFuture> b;
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
Object r;
CompletableFuture> z;
if ((r = (z = this).result) != null || (r = (z = b).result) != null)
return z.uniRunNow(r, e, f);
CompletableFuture d = newIncompleteFuture();
orpush(b, new OrRun(e, d, this, b, f));
return d;
}
/** Completion for an anyOf input future. */
@SuppressWarnings("serial")
static class AnyOf extends Completion {
CompletableFuture