ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.208
Committed: Wed Aug 24 21:46:18 2016 UTC (7 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.207: +1 -1 lines
Log Message:
use standard javadoc at-clause order

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent;
8
9 import java.lang.invoke.MethodHandles;
10 import java.lang.invoke.VarHandle;
11 import java.util.concurrent.locks.LockSupport;
12 import java.util.function.BiConsumer;
13 import java.util.function.BiFunction;
14 import java.util.function.Consumer;
15 import java.util.function.Function;
16 import java.util.function.Supplier;
17
18 /**
19 * A {@link Future} that may be explicitly completed (setting its
20 * value and status), and may be used as a {@link CompletionStage},
21 * supporting dependent functions and actions that trigger upon its
22 * completion.
23 *
24 * <p>When two or more threads attempt to
25 * {@link #complete complete},
26 * {@link #completeExceptionally completeExceptionally}, or
27 * {@link #cancel cancel}
28 * a CompletableFuture, only one of them succeeds.
29 *
30 * <p>In addition to these and related methods for directly
31 * manipulating status and results, CompletableFuture implements
32 * interface {@link CompletionStage} with the following policies: <ul>
33 *
34 * <li>Actions supplied for dependent completions of
35 * <em>non-async</em> methods may be performed by the thread that
36 * completes the current CompletableFuture, or by any other caller of
37 * a completion method.
38 *
39 * <li>All <em>async</em> methods without an explicit Executor
40 * argument are performed using the {@link ForkJoinPool#commonPool()}
41 * (unless it does not support a parallelism level of at least two, in
42 * which case, a new Thread is created to run each task). This may be
43 * overridden for non-static methods in subclasses by defining method
44 * {@link #defaultExecutor()}. To simplify monitoring, debugging,
45 * and tracking, all generated asynchronous tasks are instances of the
46 * marker interface {@link AsynchronousCompletionTask}. Operations
47 * with time-delays can use adapter methods defined in this class, for
48 * example: {@code supplyAsync(supplier, delayedExecutor(timeout,
49 * timeUnit))}. To support methods with delays and timeouts, this
50 * class maintains at most one daemon thread for triggering and
51 * cancelling actions, not for running them.
52 *
53 * <li>All CompletionStage methods are implemented independently of
54 * other public methods, so the behavior of one method is not impacted
55 * by overrides of others in subclasses.
56 *
57 * <li>All CompletionStage methods return CompletableFutures. To
58 * restrict usages to only those methods defined in interface
59 * CompletionStage, use method {@link #minimalCompletionStage}. Or to
60 * ensure only that clients do not themselves modify a future, use
61 * method {@link #copy}.
62 * </ul>
63 *
64 * <p>CompletableFuture also implements {@link Future} with the following
65 * policies: <ul>
66 *
67 * <li>Since (unlike {@link FutureTask}) this class has no direct
68 * control over the computation that causes it to be completed,
69 * cancellation is treated as just another form of exceptional
70 * completion. Method {@link #cancel cancel} has the same effect as
71 * {@code completeExceptionally(new CancellationException())}. Method
72 * {@link #isCompletedExceptionally} can be used to determine if a
73 * CompletableFuture completed in any exceptional fashion.
74 *
75 * <li>In case of exceptional completion with a CompletionException,
76 * methods {@link #get()} and {@link #get(long, TimeUnit)} throw an
77 * {@link ExecutionException} with the same cause as held in the
78 * corresponding CompletionException. To simplify usage in most
79 * contexts, this class also defines methods {@link #join()} and
80 * {@link #getNow} that instead throw the CompletionException directly
81 * in these cases.
82 * </ul>
83 *
84 * <p>Arguments used to pass a completion result (that is, for
85 * parameters of type {@code T}) for methods accepting them may be
86 * null, but passing a null value for any other parameter will result
87 * in a {@link NullPointerException} being thrown.
88 *
89 * <p>Subclasses of this class should normally override the "virtual
90 * constructor" method {@link #newIncompleteFuture}, which establishes
91 * the concrete type returned by CompletionStage methods. For example,
92 * here is a class that substitutes a different default Executor and
93 * disables the {@code obtrude} methods:
94 *
95 * <pre> {@code
96 * class MyCompletableFuture<T> extends CompletableFuture<T> {
97 * static final Executor myExecutor = ...;
98 * public MyCompletableFuture() { }
99 * public <U> CompletableFuture<U> newIncompleteFuture() {
100 * return new MyCompletableFuture<U>(); }
101 * public Executor defaultExecutor() {
102 * return myExecutor; }
103 * public void obtrudeValue(T value) {
104 * throw new UnsupportedOperationException(); }
105 * public void obtrudeException(Throwable ex) {
106 * throw new UnsupportedOperationException(); }
107 * }}</pre>
108 *
109 * @author Doug Lea
110 * @param <T> The result type returned by this future's {@code join}
111 * and {@code get} methods
112 * @since 1.8
113 */
114 public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {
115
116 /*
117 * Overview:
118 *
119 * A CompletableFuture may have dependent completion actions,
120 * collected in a linked stack. It atomically completes by CASing
121 * a result field, and then pops off and runs those actions. This
122 * applies across normal vs exceptional outcomes, sync vs async
123 * actions, binary triggers, and various forms of completions.
124 *
125 * Non-nullness of volatile field "result" indicates done. It may
126 * be set directly if known to be thread-confined, else via CAS.
127 * An AltResult is used to box null as a result, as well as to
128 * hold exceptions. Using a single field makes completion simple
129 * to detect and trigger. Result encoding and decoding is
130 * straightforward but tedious and adds to the sprawl of trapping
131 * and associating exceptions with targets. Minor simplifications
132 * rely on (static) NIL (to box null results) being the only
133 * AltResult with a null exception field, so we don't usually need
134 * explicit comparisons. Even though some of the generics casts
135 * are unchecked (see SuppressWarnings annotations), they are
136 * placed to be appropriate even if checked.
137 *
138 * Dependent actions are represented by Completion objects linked
139 * as Treiber stacks headed by field "stack". There are Completion
140 * classes for each kind of action, grouped into:
141 * - single-input (UniCompletion),
142 * - two-input (BiCompletion),
143 * - projected (BiCompletions using exactly one of two inputs),
144 * - shared (CoCompletion, used by the second of two sources),
145 * - zero-input source actions,
146 * - Signallers that unblock waiters.
147 * Class Completion extends ForkJoinTask to enable async execution
148 * (adding no space overhead because we exploit its "tag" methods
149 * to maintain claims). It is also declared as Runnable to allow
150 * usage with arbitrary executors.
151 *
152 * Support for each kind of CompletionStage relies on a separate
153 * class, along with two CompletableFuture methods:
154 *
155 * * A Completion class with name X corresponding to function,
156 * prefaced with "Uni", "Bi", or "Or". Each class contains
157 * fields for source(s), actions, and dependent. They are
158 * boringly similar, differing from others only with respect to
159 * underlying functional forms. We do this so that users don't
160 * encounter layers of adapters in common usages.
161 *
162 * * Boolean CompletableFuture method x(...) (for example
163 * biApply) takes all of the arguments needed to check that an
164 * action is triggerable, and then either runs the action or
165 * arranges its async execution by executing its Completion
166 * argument, if present. The method returns true if known to be
167 * complete.
168 *
169 * * Completion method tryFire(int mode) invokes the associated x
170 * method with its held arguments, and on success cleans up.
171 * The mode argument allows tryFire to be called twice (SYNC,
172 * then ASYNC); the first to screen and trap exceptions while
173 * arranging to execute, and the second when called from a task.
174 * (A few classes are not used async so take slightly different
175 * forms.) The claim() callback suppresses function invocation
176 * if already claimed by another thread.
177 *
178 * * Some classes (for example UniApply) have separate handling
179 * code for when known to be thread-confined ("now" methods) and
180 * for when shared (in tryFire), for efficiency.
181 *
182 * * CompletableFuture method xStage(...) is called from a public
183 * stage method of CompletableFuture f. It screens user
184 * arguments and invokes and/or creates the stage object. If
185 * not async and already triggerable, the action is run
186 * immediately. Otherwise a Completion c is created, and
187 * submitted to the executor if triggerable, or pushed onto f's
188 * stack if not. Completion actions are started via c.tryFire.
189 * We recheck after pushing to a source future's stack to cover
190 * possible races if the source completes while pushing.
191 * Classes with two inputs (for example BiApply) deal with races
192 * across both while pushing actions. The second completion is
193 * a CoCompletion pointing to the first, shared so that at most
194 * one performs the action. The multiple-arity methods allOf
195 * does this pairwise to form trees of completions. Method
196 * anyOf is handled differently from allOf because completion of
197 * any source should trigger a cleanStack of other sources.
198 * Each AnyOf completion can reach others via a shared array.
199 *
200 * Note that the generic type parameters of methods vary according
201 * to whether "this" is a source, dependent, or completion.
202 *
203 * Method postComplete is called upon completion unless the target
204 * is guaranteed not to be observable (i.e., not yet returned or
205 * linked). Multiple threads can call postComplete, which
206 * atomically pops each dependent action, and tries to trigger it
207 * via method tryFire, in NESTED mode. Triggering can propagate
208 * recursively, so NESTED mode returns its completed dependent (if
209 * one exists) for further processing by its caller (see method
210 * postFire).
211 *
212 * Blocking methods get() and join() rely on Signaller Completions
213 * that wake up waiting threads. The mechanics are similar to
214 * Treiber stack wait-nodes used in FutureTask, Phaser, and
215 * SynchronousQueue. See their internal documentation for
216 * algorithmic details.
217 *
218 * Without precautions, CompletableFutures would be prone to
219 * garbage accumulation as chains of Completions build up, each
220 * pointing back to its sources. So we null out fields as soon as
221 * possible. The screening checks needed anyway harmlessly ignore
222 * null arguments that may have been obtained during races with
223 * threads nulling out fields. We also try to unlink non-isLive
224 * (fired or cancelled) Completions from stacks that might
225 * otherwise never be popped: Method cleanStack always unlinks non
226 * isLive completions from the head of stack; others may
227 * occasionally remain if racing with other cancellations or
228 * removals.
229 *
230 * Completion fields need not be declared as final or volatile
231 * because they are only visible to other threads upon safe
232 * publication.
233 */
234
235 volatile Object result; // Either the result or boxed AltResult
236 volatile Completion stack; // Top of Treiber stack of dependent actions
237
238 final boolean internalComplete(Object r) { // CAS from null to r
239 return RESULT.compareAndSet(this, null, r);
240 }
241
242 /** Returns true if successfully pushed c onto stack. */
243 final boolean tryPushStack(Completion c) {
244 Completion h = stack;
245 NEXT.set(c, h); // CAS piggyback
246 return STACK.compareAndSet(this, h, c);
247 }
248
249 /** Unconditionally pushes c onto stack, retrying if necessary. */
250 final void pushStack(Completion c) {
251 do {} while (!tryPushStack(c));
252 }
253
254 /* ------------- Encoding and decoding outcomes -------------- */
255
256 static final class AltResult { // See above
257 final Throwable ex; // null only for NIL
258 AltResult(Throwable x) { this.ex = x; }
259 }
260
261 /** The encoding of the null value. */
262 static final AltResult NIL = new AltResult(null);
263
264 /** Completes with the null value, unless already completed. */
265 final boolean completeNull() {
266 return RESULT.compareAndSet(this, null, NIL);
267 }
268
269 /** Returns the encoding of the given non-exceptional value. */
270 final Object encodeValue(T t) {
271 return (t == null) ? NIL : t;
272 }
273
274 /** Completes with a non-exceptional result, unless already completed. */
275 final boolean completeValue(T t) {
276 return RESULT.compareAndSet(this, null, (t == null) ? NIL : t);
277 }
278
279 /**
280 * Returns the encoding of the given (non-null) exception as a
281 * wrapped CompletionException unless it is one already.
282 */
283 static AltResult encodeThrowable(Throwable x) {
284 return new AltResult((x instanceof CompletionException) ? x :
285 new CompletionException(x));
286 }
287
288 /** Completes with an exceptional result, unless already completed. */
289 final boolean completeThrowable(Throwable x) {
290 return RESULT.compareAndSet(this, null, encodeThrowable(x));
291 }
292
293 /**
294 * Returns the encoding of the given (non-null) exception as a
295 * wrapped CompletionException unless it is one already. May
296 * return the given Object r (which must have been the result of a
297 * source future) if it is equivalent, i.e. if this is a simple
298 * relay of an existing CompletionException.
299 */
300 static Object encodeThrowable(Throwable x, Object r) {
301 if (!(x instanceof CompletionException))
302 x = new CompletionException(x);
303 else if (r instanceof AltResult && x == ((AltResult)r).ex)
304 return r;
305 return new AltResult(x);
306 }
307
308 /**
309 * Completes with the given (non-null) exceptional result as a
310 * wrapped CompletionException unless it is one already, unless
311 * already completed. May complete with the given Object r
312 * (which must have been the result of a source future) if it is
313 * equivalent, i.e. if this is a simple propagation of an
314 * existing CompletionException.
315 */
316 final boolean completeThrowable(Throwable x, Object r) {
317 return RESULT.compareAndSet(this, null, encodeThrowable(x, r));
318 }
319
320 /**
321 * Returns the encoding of the given arguments: if the exception
322 * is non-null, encodes as AltResult. Otherwise uses the given
323 * value, boxed as NIL if null.
324 */
325 Object encodeOutcome(T t, Throwable x) {
326 return (x == null) ? (t == null) ? NIL : t : encodeThrowable(x);
327 }
328
329 /**
330 * Returns the encoding of a copied outcome; if exceptional,
331 * rewraps as a CompletionException, else returns argument.
332 */
333 static Object encodeRelay(Object r) {
334 Throwable x;
335 if (r instanceof AltResult
336 && (x = ((AltResult)r).ex) != null
337 && !(x instanceof CompletionException))
338 r = new AltResult(new CompletionException(x));
339 return r;
340 }
341
342 /**
343 * Completes with r or a copy of r, unless already completed.
344 * If exceptional, r is first coerced to a CompletionException.
345 */
346 final boolean completeRelay(Object r) {
347 return RESULT.compareAndSet(this, null, encodeRelay(r));
348 }
349
350 /**
351 * Reports result using Future.get conventions.
352 */
353 private static Object reportGet(Object r)
354 throws InterruptedException, ExecutionException {
355 if (r == null) // by convention below, null means interrupted
356 throw new InterruptedException();
357 if (r instanceof AltResult) {
358 Throwable x, cause;
359 if ((x = ((AltResult)r).ex) == null)
360 return null;
361 if (x instanceof CancellationException)
362 throw (CancellationException)x;
363 if ((x instanceof CompletionException) &&
364 (cause = x.getCause()) != null)
365 x = cause;
366 throw new ExecutionException(x);
367 }
368 return r;
369 }
370
371 /**
372 * Decodes outcome to return result or throw unchecked exception.
373 */
374 private static Object reportJoin(Object r) {
375 if (r instanceof AltResult) {
376 Throwable x;
377 if ((x = ((AltResult)r).ex) == null)
378 return null;
379 if (x instanceof CancellationException)
380 throw (CancellationException)x;
381 if (x instanceof CompletionException)
382 throw (CompletionException)x;
383 throw new CompletionException(x);
384 }
385 return r;
386 }
387
388 /* ------------- Async task preliminaries -------------- */
389
390 /**
391 * A marker interface identifying asynchronous tasks produced by
392 * {@code async} methods. This may be useful for monitoring,
393 * debugging, and tracking asynchronous activities.
394 *
395 * @since 1.8
396 */
397 public static interface AsynchronousCompletionTask {
398 }
399
400 private static final boolean USE_COMMON_POOL =
401 (ForkJoinPool.getCommonPoolParallelism() > 1);
402
403 /**
404 * Default executor -- ForkJoinPool.commonPool() unless it cannot
405 * support parallelism.
406 */
407 private static final Executor ASYNC_POOL = USE_COMMON_POOL ?
408 ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
409
410 /** Fallback if ForkJoinPool.commonPool() cannot support parallelism */
411 static final class ThreadPerTaskExecutor implements Executor {
412 public void execute(Runnable r) { new Thread(r).start(); }
413 }
414
415 /**
416 * Null-checks user executor argument, and translates uses of
417 * commonPool to ASYNC_POOL in case parallelism disabled.
418 */
419 static Executor screenExecutor(Executor e) {
420 if (!USE_COMMON_POOL && e == ForkJoinPool.commonPool())
421 return ASYNC_POOL;
422 if (e == null) throw new NullPointerException();
423 return e;
424 }
425
426 // Modes for Completion.tryFire. Signedness matters.
427 static final int SYNC = 0;
428 static final int ASYNC = 1;
429 static final int NESTED = -1;
430
431 /* ------------- Base Completion classes and operations -------------- */
432
433 @SuppressWarnings("serial")
434 abstract static class Completion extends ForkJoinTask<Void>
435 implements Runnable, AsynchronousCompletionTask {
436 volatile Completion next; // Treiber stack link
437
438 /**
439 * Performs completion action if triggered, returning a
440 * dependent that may need propagation, if one exists.
441 *
442 * @param mode SYNC, ASYNC, or NESTED
443 */
444 abstract CompletableFuture<?> tryFire(int mode);
445
446 /** Returns true if possibly still triggerable. Used by cleanStack. */
447 abstract boolean isLive();
448
449 public final void run() { tryFire(ASYNC); }
450 public final boolean exec() { tryFire(ASYNC); return false; }
451 public final Void getRawResult() { return null; }
452 public final void setRawResult(Void v) {}
453 }
454
455 /**
456 * Pops and tries to trigger all reachable dependents. Call only
457 * when known to be done.
458 */
459 final void postComplete() {
460 /*
461 * On each step, variable f holds current dependents to pop
462 * and run. It is extended along only one path at a time,
463 * pushing others to avoid unbounded recursion.
464 */
465 CompletableFuture<?> f = this; Completion h;
466 while ((h = f.stack) != null ||
467 (f != this && (h = (f = this).stack) != null)) {
468 CompletableFuture<?> d; Completion t;
469 if (STACK.compareAndSet(f, h, t = h.next)) {
470 if (t != null) {
471 if (f != this) {
472 pushStack(h);
473 continue;
474 }
475 NEXT.compareAndSet(h, t, null); // try to detach
476 }
477 f = (d = h.tryFire(NESTED)) == null ? this : d;
478 }
479 }
480 }
481
482 /** Traverses stack and unlinks one or more dead Completions, if found. */
483 final void cleanStack() {
484 Completion p = stack;
485 // ensure head of stack live
486 for (boolean unlinked = false;;) {
487 if (p == null)
488 return;
489 else if (p.isLive()) {
490 if (unlinked)
491 return;
492 else
493 break;
494 }
495 else if (STACK.weakCompareAndSetVolatile(this, p, (p = p.next)))
496 unlinked = true;
497 else
498 p = stack;
499 }
500 // try to unlink first non-live
501 for (Completion q = p.next; q != null;) {
502 Completion s = q.next;
503 if (q.isLive()) {
504 p = q;
505 q = s;
506 } else if (NEXT.weakCompareAndSetVolatile(p, q, s))
507 break;
508 else
509 q = p.next;
510 }
511 }
512
513 /* ------------- One-input Completions -------------- */
514
515 /** A Completion with a source, dependent, and executor. */
516 @SuppressWarnings("serial")
517 abstract static class UniCompletion<T,V> extends Completion {
518 Executor executor; // executor to use (null if none)
519 CompletableFuture<V> dep; // the dependent to complete
520 CompletableFuture<T> src; // source for action
521
522 UniCompletion(Executor executor, CompletableFuture<V> dep,
523 CompletableFuture<T> src) {
524 this.executor = executor; this.dep = dep; this.src = src;
525 }
526
527 /**
528 * Returns true if action can be run. Call only when known to
529 * be triggerable. Uses FJ tag bit to ensure that only one
530 * thread claims ownership. If async, starts as task -- a
531 * later call to tryFire will run action.
532 */
533 final boolean claim() {
534 Executor e = executor;
535 if (compareAndSetForkJoinTaskTag((short)0, (short)1)) {
536 if (e == null)
537 return true;
538 executor = null; // disable
539 e.execute(this);
540 }
541 return false;
542 }
543
544 final boolean isLive() { return dep != null; }
545 }
546
547 /**
548 * Pushes the given completion unless it completes while trying.
549 * Caller should first check that result is null.
550 */
551 final void unipush(Completion c) {
552 if (c != null) {
553 while (!tryPushStack(c)) {
554 if (result != null) {
555 NEXT.set(c, null);
556 break;
557 }
558 }
559 if (result != null)
560 c.tryFire(SYNC);
561 }
562 }
563
564 /**
565 * Post-processing by dependent after successful UniCompletion tryFire.
566 * Tries to clean stack of source a, and then either runs postComplete
567 * or returns this to caller, depending on mode.
568 */
569 final CompletableFuture<T> postFire(CompletableFuture<?> a, int mode) {
570 if (a != null && a.stack != null) {
571 Object r;
572 if ((r = a.result) == null)
573 a.cleanStack();
574 if (mode >= 0 && (r != null || a.result != null))
575 a.postComplete();
576 }
577 if (result != null && stack != null) {
578 if (mode < 0)
579 return this;
580 else
581 postComplete();
582 }
583 return null;
584 }
585
586 @SuppressWarnings("serial")
587 static final class UniApply<T,V> extends UniCompletion<T,V> {
588 Function<? super T,? extends V> fn;
589 UniApply(Executor executor, CompletableFuture<V> dep,
590 CompletableFuture<T> src,
591 Function<? super T,? extends V> fn) {
592 super(executor, dep, src); this.fn = fn;
593 }
594 final CompletableFuture<V> tryFire(int mode) {
595 CompletableFuture<V> d; CompletableFuture<T> a;
596 Object r; Throwable x; Function<? super T,? extends V> f;
597 if ((d = dep) == null || (f = fn) == null
598 || (a = src) == null || (r = a.result) == null)
599 return null;
600 tryComplete: if (d.result == null) {
601 if (r instanceof AltResult) {
602 if ((x = ((AltResult)r).ex) != null) {
603 d.completeThrowable(x, r);
604 break tryComplete;
605 }
606 r = null;
607 }
608 try {
609 if (mode <= 0 && !claim())
610 return null;
611 else {
612 @SuppressWarnings("unchecked") T t = (T) r;
613 d.completeValue(f.apply(t));
614 }
615 } catch (Throwable ex) {
616 d.completeThrowable(ex);
617 }
618 }
619 dep = null; src = null; fn = null;
620 return d.postFire(a, mode);
621 }
622 }
623
624 private <V> CompletableFuture<V> uniApplyStage(
625 Executor e, Function<? super T,? extends V> f) {
626 if (f == null) throw new NullPointerException();
627 Object r;
628 if ((r = result) != null)
629 return uniApplyNow(r, e, f);
630 CompletableFuture<V> d = newIncompleteFuture();
631 unipush(new UniApply<T,V>(e, d, this, f));
632 return d;
633 }
634
635 private <V> CompletableFuture<V> uniApplyNow(
636 Object r, Executor e, Function<? super T,? extends V> f) {
637 Throwable x;
638 CompletableFuture<V> d = newIncompleteFuture();
639 if (r instanceof AltResult) {
640 if ((x = ((AltResult)r).ex) != null) {
641 d.result = encodeThrowable(x, r);
642 return d;
643 }
644 r = null;
645 }
646 try {
647 if (e != null) {
648 e.execute(new UniApply<T,V>(null, d, this, f));
649 } else {
650 @SuppressWarnings("unchecked") T t = (T) r;
651 d.result = d.encodeValue(f.apply(t));
652 }
653 } catch (Throwable ex) {
654 d.result = encodeThrowable(ex);
655 }
656 return d;
657 }
658
659 @SuppressWarnings("serial")
660 static final class UniAccept<T> extends UniCompletion<T,Void> {
661 Consumer<? super T> fn;
662 UniAccept(Executor executor, CompletableFuture<Void> dep,
663 CompletableFuture<T> src, Consumer<? super T> fn) {
664 super(executor, dep, src); this.fn = fn;
665 }
666 final CompletableFuture<Void> tryFire(int mode) {
667 CompletableFuture<Void> d; CompletableFuture<T> a;
668 Object r; Throwable x; Consumer<? super T> f;
669 if ((d = dep) == null || (f = fn) == null
670 || (a = src) == null || (r = a.result) == null)
671 return null;
672 tryComplete: if (d.result == null) {
673 if (r instanceof AltResult) {
674 if ((x = ((AltResult)r).ex) != null) {
675 d.completeThrowable(x, r);
676 break tryComplete;
677 }
678 r = null;
679 }
680 try {
681 if (mode <= 0 && !claim())
682 return null;
683 else {
684 @SuppressWarnings("unchecked") T t = (T) r;
685 f.accept(t);
686 d.completeNull();
687 }
688 } catch (Throwable ex) {
689 d.completeThrowable(ex);
690 }
691 }
692 dep = null; src = null; fn = null;
693 return d.postFire(a, mode);
694 }
695 }
696
697 private CompletableFuture<Void> uniAcceptStage(Executor e,
698 Consumer<? super T> f) {
699 if (f == null) throw new NullPointerException();
700 Object r;
701 if ((r = result) != null)
702 return uniAcceptNow(r, e, f);
703 CompletableFuture<Void> d = newIncompleteFuture();
704 unipush(new UniAccept<T>(e, d, this, f));
705 return d;
706 }
707
708 private CompletableFuture<Void> uniAcceptNow(
709 Object r, Executor e, Consumer<? super T> f) {
710 Throwable x;
711 CompletableFuture<Void> d = newIncompleteFuture();
712 if (r instanceof AltResult) {
713 if ((x = ((AltResult)r).ex) != null) {
714 d.result = encodeThrowable(x, r);
715 return d;
716 }
717 r = null;
718 }
719 try {
720 if (e != null) {
721 e.execute(new UniAccept<T>(null, d, this, f));
722 } else {
723 @SuppressWarnings("unchecked") T t = (T) r;
724 f.accept(t);
725 d.result = NIL;
726 }
727 } catch (Throwable ex) {
728 d.result = encodeThrowable(ex);
729 }
730 return d;
731 }
732
733 @SuppressWarnings("serial")
734 static final class UniRun<T> extends UniCompletion<T,Void> {
735 Runnable fn;
736 UniRun(Executor executor, CompletableFuture<Void> dep,
737 CompletableFuture<T> src, Runnable fn) {
738 super(executor, dep, src); this.fn = fn;
739 }
740 final CompletableFuture<Void> tryFire(int mode) {
741 CompletableFuture<Void> d; CompletableFuture<T> a;
742 Object r; Throwable x; Runnable f;
743 if ((d = dep) == null || (f = fn) == null
744 || (a = src) == null || (r = a.result) == null)
745 return null;
746 if (d.result == null) {
747 if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
748 d.completeThrowable(x, r);
749 else
750 try {
751 if (mode <= 0 && !claim())
752 return null;
753 else {
754 f.run();
755 d.completeNull();
756 }
757 } catch (Throwable ex) {
758 d.completeThrowable(ex);
759 }
760 }
761 dep = null; src = null; fn = null;
762 return d.postFire(a, mode);
763 }
764 }
765
766 private CompletableFuture<Void> uniRunStage(Executor e, Runnable f) {
767 if (f == null) throw new NullPointerException();
768 Object r;
769 if ((r = result) != null)
770 return uniRunNow(r, e, f);
771 CompletableFuture<Void> d = newIncompleteFuture();
772 unipush(new UniRun<T>(e, d, this, f));
773 return d;
774 }
775
776 private CompletableFuture<Void> uniRunNow(Object r, Executor e, Runnable f) {
777 Throwable x;
778 CompletableFuture<Void> d = newIncompleteFuture();
779 if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
780 d.result = encodeThrowable(x, r);
781 else
782 try {
783 if (e != null) {
784 e.execute(new UniRun<T>(null, d, this, f));
785 } else {
786 f.run();
787 d.result = NIL;
788 }
789 } catch (Throwable ex) {
790 d.result = encodeThrowable(ex);
791 }
792 return d;
793 }
794
795 @SuppressWarnings("serial")
796 static final class UniWhenComplete<T> extends UniCompletion<T,T> {
797 BiConsumer<? super T, ? super Throwable> fn;
798 UniWhenComplete(Executor executor, CompletableFuture<T> dep,
799 CompletableFuture<T> src,
800 BiConsumer<? super T, ? super Throwable> fn) {
801 super(executor, dep, src); this.fn = fn;
802 }
803 final CompletableFuture<T> tryFire(int mode) {
804 CompletableFuture<T> d; CompletableFuture<T> a;
805 Object r; BiConsumer<? super T, ? super Throwable> f;
806 if ((d = dep) == null || (f = fn) == null
807 || (a = src) == null || (r = a.result) == null
808 || !d.uniWhenComplete(r, f, mode > 0 ? null : this))
809 return null;
810 dep = null; src = null; fn = null;
811 return d.postFire(a, mode);
812 }
813 }
814
815 final boolean uniWhenComplete(Object r,
816 BiConsumer<? super T,? super Throwable> f,
817 UniWhenComplete<T> c) {
818 T t; Throwable x = null;
819 if (result == null) {
820 try {
821 if (c != null && !c.claim())
822 return false;
823 if (r instanceof AltResult) {
824 x = ((AltResult)r).ex;
825 t = null;
826 } else {
827 @SuppressWarnings("unchecked") T tr = (T) r;
828 t = tr;
829 }
830 f.accept(t, x);
831 if (x == null) {
832 internalComplete(r);
833 return true;
834 }
835 } catch (Throwable ex) {
836 if (x == null)
837 x = ex;
838 else if (x != ex)
839 x.addSuppressed(ex);
840 }
841 completeThrowable(x, r);
842 }
843 return true;
844 }
845
846 private CompletableFuture<T> uniWhenCompleteStage(
847 Executor e, BiConsumer<? super T, ? super Throwable> f) {
848 if (f == null) throw new NullPointerException();
849 CompletableFuture<T> d = newIncompleteFuture();
850 Object r;
851 if ((r = result) == null)
852 unipush(new UniWhenComplete<T>(e, d, this, f));
853 else if (e == null)
854 d.uniWhenComplete(r, f, null);
855 else {
856 try {
857 e.execute(new UniWhenComplete<T>(null, d, this, f));
858 } catch (Throwable ex) {
859 d.result = encodeThrowable(ex);
860 }
861 }
862 return d;
863 }
864
865 @SuppressWarnings("serial")
866 static final class UniHandle<T,V> extends UniCompletion<T,V> {
867 BiFunction<? super T, Throwable, ? extends V> fn;
868 UniHandle(Executor executor, CompletableFuture<V> dep,
869 CompletableFuture<T> src,
870 BiFunction<? super T, Throwable, ? extends V> fn) {
871 super(executor, dep, src); this.fn = fn;
872 }
873 final CompletableFuture<V> tryFire(int mode) {
874 CompletableFuture<V> d; CompletableFuture<T> a;
875 Object r; BiFunction<? super T, Throwable, ? extends V> f;
876 if ((d = dep) == null || (f = fn) == null
877 || (a = src) == null || (r = a.result) == null
878 || !d.uniHandle(r, f, mode > 0 ? null : this))
879 return null;
880 dep = null; src = null; fn = null;
881 return d.postFire(a, mode);
882 }
883 }
884
885 final <S> boolean uniHandle(Object r,
886 BiFunction<? super S, Throwable, ? extends T> f,
887 UniHandle<S,T> c) {
888 S s; Throwable x;
889 if (result == null) {
890 try {
891 if (c != null && !c.claim())
892 return false;
893 if (r instanceof AltResult) {
894 x = ((AltResult)r).ex;
895 s = null;
896 } else {
897 x = null;
898 @SuppressWarnings("unchecked") S ss = (S) r;
899 s = ss;
900 }
901 completeValue(f.apply(s, x));
902 } catch (Throwable ex) {
903 completeThrowable(ex);
904 }
905 }
906 return true;
907 }
908
909 private <V> CompletableFuture<V> uniHandleStage(
910 Executor e, BiFunction<? super T, Throwable, ? extends V> f) {
911 if (f == null) throw new NullPointerException();
912 CompletableFuture<V> d = newIncompleteFuture();
913 Object r;
914 if ((r = result) == null)
915 unipush(new UniHandle<T,V>(e, d, this, f));
916 else if (e == null)
917 d.uniHandle(r, f, null);
918 else {
919 try {
920 e.execute(new UniHandle<T,V>(null, d, this, f));
921 } catch (Throwable ex) {
922 d.result = encodeThrowable(ex);
923 }
924 }
925 return d;
926 }
927
928 @SuppressWarnings("serial")
929 static final class UniExceptionally<T> extends UniCompletion<T,T> {
930 Function<? super Throwable, ? extends T> fn;
931 UniExceptionally(CompletableFuture<T> dep, CompletableFuture<T> src,
932 Function<? super Throwable, ? extends T> fn) {
933 super(null, dep, src); this.fn = fn;
934 }
935 final CompletableFuture<T> tryFire(int mode) { // never ASYNC
936 // assert mode != ASYNC;
937 CompletableFuture<T> d; CompletableFuture<T> a;
938 Object r; Function<? super Throwable, ? extends T> f;
939 if ((d = dep) == null || (f = fn) == null
940 || (a = src) == null || (r = a.result) == null
941 || !d.uniExceptionally(r, f, this))
942 return null;
943 dep = null; src = null; fn = null;
944 return d.postFire(a, mode);
945 }
946 }
947
948 final boolean uniExceptionally(Object r,
949 Function<? super Throwable, ? extends T> f,
950 UniExceptionally<T> c) {
951 Throwable x;
952 if (result == null) {
953 try {
954 if (r instanceof AltResult && (x = ((AltResult)r).ex) != null) {
955 if (c != null && !c.claim())
956 return false;
957 completeValue(f.apply(x));
958 } else
959 internalComplete(r);
960 } catch (Throwable ex) {
961 completeThrowable(ex);
962 }
963 }
964 return true;
965 }
966
967 private CompletableFuture<T> uniExceptionallyStage(
968 Function<Throwable, ? extends T> f) {
969 if (f == null) throw new NullPointerException();
970 CompletableFuture<T> d = newIncompleteFuture();
971 Object r;
972 if ((r = result) == null)
973 unipush(new UniExceptionally<T>(d, this, f));
974 else
975 d.uniExceptionally(r, f, null);
976 return d;
977 }
978
979 @SuppressWarnings("serial")
980 static final class UniRelay<U, T extends U> extends UniCompletion<T,U> {
981 UniRelay(CompletableFuture<U> dep, CompletableFuture<T> src) {
982 super(null, dep, src);
983 }
984 final CompletableFuture<U> tryFire(int mode) {
985 CompletableFuture<U> d; CompletableFuture<T> a; Object r;
986 if ((d = dep) == null
987 || (a = src) == null || (r = a.result) == null)
988 return null;
989 if (d.result == null)
990 d.completeRelay(r);
991 src = null; dep = null;
992 return d.postFire(a, mode);
993 }
994 }
995
996 private static <U, T extends U> CompletableFuture<U> uniCopyStage(
997 CompletableFuture<T> src) {
998 Object r;
999 CompletableFuture<U> d = src.newIncompleteFuture();
1000 if ((r = src.result) != null)
1001 d.result = encodeRelay(r);
1002 else
1003 src.unipush(new UniRelay<U,T>(d, src));
1004 return d;
1005 }
1006
1007 private MinimalStage<T> uniAsMinimalStage() {
1008 Object r;
1009 if ((r = result) != null)
1010 return new MinimalStage<T>(encodeRelay(r));
1011 MinimalStage<T> d = new MinimalStage<T>();
1012 unipush(new UniRelay<T,T>(d, this));
1013 return d;
1014 }
1015
1016 @SuppressWarnings("serial")
1017 static final class UniCompose<T,V> extends UniCompletion<T,V> {
1018 Function<? super T, ? extends CompletionStage<V>> fn;
1019 UniCompose(Executor executor, CompletableFuture<V> dep,
1020 CompletableFuture<T> src,
1021 Function<? super T, ? extends CompletionStage<V>> fn) {
1022 super(executor, dep, src); this.fn = fn;
1023 }
1024 final CompletableFuture<V> tryFire(int mode) {
1025 CompletableFuture<V> d; CompletableFuture<T> a;
1026 Function<? super T, ? extends CompletionStage<V>> f;
1027 Object r; Throwable x;
1028 if ((d = dep) == null || (f = fn) == null
1029 || (a = src) == null || (r = a.result) == null)
1030 return null;
1031 tryComplete: if (d.result == null) {
1032 if (r instanceof AltResult) {
1033 if ((x = ((AltResult)r).ex) != null) {
1034 d.completeThrowable(x, r);
1035 break tryComplete;
1036 }
1037 r = null;
1038 }
1039 try {
1040 if (mode <= 0 && !claim())
1041 return null;
1042 @SuppressWarnings("unchecked") T t = (T) r;
1043 CompletableFuture<V> g = f.apply(t).toCompletableFuture();
1044 if ((r = g.result) != null)
1045 d.completeRelay(r);
1046 else {
1047 g.unipush(new UniRelay<V,V>(d, g));
1048 if (d.result == null)
1049 return null;
1050 }
1051 } catch (Throwable ex) {
1052 d.completeThrowable(ex);
1053 }
1054 }
1055 dep = null; src = null; fn = null;
1056 return d.postFire(a, mode);
1057 }
1058 }
1059
1060 private <V> CompletableFuture<V> uniComposeStage(
1061 Executor e, Function<? super T, ? extends CompletionStage<V>> f) {
1062 if (f == null) throw new NullPointerException();
1063 CompletableFuture<V> d = newIncompleteFuture();
1064 Object r, s; Throwable x;
1065 if ((r = result) == null)
1066 unipush(new UniCompose<T,V>(e, d, this, f));
1067 else if (e == null) {
1068 if (r instanceof AltResult) {
1069 if ((x = ((AltResult)r).ex) != null) {
1070 d.result = encodeThrowable(x, r);
1071 return d;
1072 }
1073 r = null;
1074 }
1075 try {
1076 @SuppressWarnings("unchecked") T t = (T) r;
1077 CompletableFuture<V> g = f.apply(t).toCompletableFuture();
1078 if ((s = g.result) != null)
1079 d.result = encodeRelay(s);
1080 else {
1081 g.unipush(new UniRelay<V,V>(d, g));
1082 }
1083 } catch (Throwable ex) {
1084 d.result = encodeThrowable(ex);
1085 }
1086 }
1087 else
1088 try {
1089 e.execute(new UniCompose<T,V>(null, d, this, f));
1090 } catch (Throwable ex) {
1091 d.result = encodeThrowable(ex);
1092 }
1093 return d;
1094 }
1095
1096 /* ------------- Two-input Completions -------------- */
1097
1098 /** A Completion for an action with two sources */
1099 @SuppressWarnings("serial")
1100 abstract static class BiCompletion<T,U,V> extends UniCompletion<T,V> {
1101 CompletableFuture<U> snd; // second source for action
1102 BiCompletion(Executor executor, CompletableFuture<V> dep,
1103 CompletableFuture<T> src, CompletableFuture<U> snd) {
1104 super(executor, dep, src); this.snd = snd;
1105 }
1106 }
1107
1108 /** A Completion delegating to a BiCompletion */
1109 @SuppressWarnings("serial")
1110 static final class CoCompletion extends Completion {
1111 BiCompletion<?,?,?> base;
1112 CoCompletion(BiCompletion<?,?,?> base) { this.base = base; }
1113 final CompletableFuture<?> tryFire(int mode) {
1114 BiCompletion<?,?,?> c; CompletableFuture<?> d;
1115 if ((c = base) == null || (d = c.tryFire(mode)) == null)
1116 return null;
1117 base = null; // detach
1118 return d;
1119 }
1120 final boolean isLive() {
1121 BiCompletion<?,?,?> c;
1122 return (c = base) != null
1123 // && c.isLive()
1124 && c.dep != null;
1125 }
1126 }
1127
1128 /**
1129 * Pushes completion to this and b unless both done.
1130 * Caller should first check that either result or b.result is null.
1131 */
1132 final void bipush(CompletableFuture<?> b, BiCompletion<?,?,?> c) {
1133 if (c != null) {
1134 while (result == null) {
1135 if (tryPushStack(c)) {
1136 if (b.result == null)
1137 b.unipush(new CoCompletion(c));
1138 else if (result != null)
1139 c.tryFire(SYNC);
1140 return;
1141 }
1142 }
1143 b.unipush(c);
1144 }
1145 }
1146
1147 /** Post-processing after successful BiCompletion tryFire. */
1148 final CompletableFuture<T> postFire(CompletableFuture<?> a,
1149 CompletableFuture<?> b, int mode) {
1150 if (b != null && b.stack != null) { // clean second source
1151 Object r;
1152 if ((r = b.result) == null)
1153 b.cleanStack();
1154 if (mode >= 0 && (r != null || b.result != null))
1155 b.postComplete();
1156 }
1157 return postFire(a, mode);
1158 }
1159
1160 @SuppressWarnings("serial")
1161 static final class BiApply<T,U,V> extends BiCompletion<T,U,V> {
1162 BiFunction<? super T,? super U,? extends V> fn;
1163 BiApply(Executor executor, CompletableFuture<V> dep,
1164 CompletableFuture<T> src, CompletableFuture<U> snd,
1165 BiFunction<? super T,? super U,? extends V> fn) {
1166 super(executor, dep, src, snd); this.fn = fn;
1167 }
1168 final CompletableFuture<V> tryFire(int mode) {
1169 CompletableFuture<V> d;
1170 CompletableFuture<T> a;
1171 CompletableFuture<U> b;
1172 Object r, s; BiFunction<? super T,? super U,? extends V> f;
1173 if ((d = dep) == null || (f = fn) == null
1174 || (a = src) == null || (r = a.result) == null
1175 || (b = snd) == null || (s = b.result) == null
1176 || !d.biApply(r, s, f, mode > 0 ? null : this))
1177 return null;
1178 dep = null; src = null; snd = null; fn = null;
1179 return d.postFire(a, b, mode);
1180 }
1181 }
1182
1183 final <R,S> boolean biApply(Object r, Object s,
1184 BiFunction<? super R,? super S,? extends T> f,
1185 BiApply<R,S,T> c) {
1186 Throwable x;
1187 tryComplete: if (result == null) {
1188 if (r instanceof AltResult) {
1189 if ((x = ((AltResult)r).ex) != null) {
1190 completeThrowable(x, r);
1191 break tryComplete;
1192 }
1193 r = null;
1194 }
1195 if (s instanceof AltResult) {
1196 if ((x = ((AltResult)s).ex) != null) {
1197 completeThrowable(x, s);
1198 break tryComplete;
1199 }
1200 s = null;
1201 }
1202 try {
1203 if (c != null && !c.claim())
1204 return false;
1205 @SuppressWarnings("unchecked") R rr = (R) r;
1206 @SuppressWarnings("unchecked") S ss = (S) s;
1207 completeValue(f.apply(rr, ss));
1208 } catch (Throwable ex) {
1209 completeThrowable(ex);
1210 }
1211 }
1212 return true;
1213 }
1214
1215 private <U,V> CompletableFuture<V> biApplyStage(
1216 Executor e, CompletionStage<U> o,
1217 BiFunction<? super T,? super U,? extends V> f) {
1218 CompletableFuture<U> b; Object r, s;
1219 if (f == null || (b = o.toCompletableFuture()) == null)
1220 throw new NullPointerException();
1221 CompletableFuture<V> d = newIncompleteFuture();
1222 if ((r = result) == null || (s = b.result) == null)
1223 bipush(b, new BiApply<T,U,V>(e, d, this, b, f));
1224 else if (e == null)
1225 d.biApply(r, s, f, null);
1226 else
1227 try {
1228 e.execute(new BiApply<T,U,V>(null, d, this, b, f));
1229 } catch (Throwable ex) {
1230 d.result = encodeThrowable(ex);
1231 }
1232 return d;
1233 }
1234
1235 @SuppressWarnings("serial")
1236 static final class BiAccept<T,U> extends BiCompletion<T,U,Void> {
1237 BiConsumer<? super T,? super U> fn;
1238 BiAccept(Executor executor, CompletableFuture<Void> dep,
1239 CompletableFuture<T> src, CompletableFuture<U> snd,
1240 BiConsumer<? super T,? super U> fn) {
1241 super(executor, dep, src, snd); this.fn = fn;
1242 }
1243 final CompletableFuture<Void> tryFire(int mode) {
1244 CompletableFuture<Void> d;
1245 CompletableFuture<T> a;
1246 CompletableFuture<U> b;
1247 Object r, s; BiConsumer<? super T,? super U> f;
1248 if ((d = dep) == null || (f = fn) == null
1249 || (a = src) == null || (r = a.result) == null
1250 || (b = snd) == null || (s = b.result) == null
1251 || !d.biAccept(r, s, f, mode > 0 ? null : this))
1252 return null;
1253 dep = null; src = null; snd = null; fn = null;
1254 return d.postFire(a, b, mode);
1255 }
1256 }
1257
1258 final <R,S> boolean biAccept(Object r, Object s,
1259 BiConsumer<? super R,? super S> f,
1260 BiAccept<R,S> c) {
1261 Throwable x;
1262 tryComplete: if (result == null) {
1263 if (r instanceof AltResult) {
1264 if ((x = ((AltResult)r).ex) != null) {
1265 completeThrowable(x, r);
1266 break tryComplete;
1267 }
1268 r = null;
1269 }
1270 if (s instanceof AltResult) {
1271 if ((x = ((AltResult)s).ex) != null) {
1272 completeThrowable(x, s);
1273 break tryComplete;
1274 }
1275 s = null;
1276 }
1277 try {
1278 if (c != null && !c.claim())
1279 return false;
1280 @SuppressWarnings("unchecked") R rr = (R) r;
1281 @SuppressWarnings("unchecked") S ss = (S) s;
1282 f.accept(rr, ss);
1283 completeNull();
1284 } catch (Throwable ex) {
1285 completeThrowable(ex);
1286 }
1287 }
1288 return true;
1289 }
1290
1291 private <U> CompletableFuture<Void> biAcceptStage(
1292 Executor e, CompletionStage<U> o,
1293 BiConsumer<? super T,? super U> f) {
1294 CompletableFuture<U> b; Object r, s;
1295 if (f == null || (b = o.toCompletableFuture()) == null)
1296 throw new NullPointerException();
1297 CompletableFuture<Void> d = newIncompleteFuture();
1298 if ((r = result) == null || (s = b.result) == null)
1299 bipush(b, new BiAccept<T,U>(e, d, this, b, f));
1300 else if (e == null)
1301 d.biAccept(r, s, f, null);
1302 else
1303 try {
1304 e.execute(new BiAccept<T,U>(null, d, this, b, f));
1305 } catch (Throwable ex) {
1306 d.result = encodeThrowable(ex);
1307 }
1308 return d;
1309 }
1310
1311 @SuppressWarnings("serial")
1312 static final class BiRun<T,U> extends BiCompletion<T,U,Void> {
1313 Runnable fn;
1314 BiRun(Executor executor, CompletableFuture<Void> dep,
1315 CompletableFuture<T> src, CompletableFuture<U> snd,
1316 Runnable fn) {
1317 super(executor, dep, src, snd); this.fn = fn;
1318 }
1319 final CompletableFuture<Void> tryFire(int mode) {
1320 CompletableFuture<Void> d;
1321 CompletableFuture<T> a;
1322 CompletableFuture<U> b;
1323 Object r, s; Runnable f;
1324 if ((d = dep) == null || (f = fn) == null
1325 || (a = src) == null || (r = a.result) == null
1326 || (b = snd) == null || (s = b.result) == null
1327 || !d.biRun(r, s, f, mode > 0 ? null : this))
1328 return null;
1329 dep = null; src = null; snd = null; fn = null;
1330 return d.postFire(a, b, mode);
1331 }
1332 }
1333
1334 final boolean biRun(Object r, Object s, Runnable f, BiRun<?,?> c) {
1335 Throwable x; Object z;
1336 if (result == null) {
1337 if ((r instanceof AltResult
1338 && (x = ((AltResult)(z = r)).ex) != null) ||
1339 (s instanceof AltResult
1340 && (x = ((AltResult)(z = s)).ex) != null))
1341 completeThrowable(x, z);
1342 else
1343 try {
1344 if (c != null && !c.claim())
1345 return false;
1346 f.run();
1347 completeNull();
1348 } catch (Throwable ex) {
1349 completeThrowable(ex);
1350 }
1351 }
1352 return true;
1353 }
1354
1355 private CompletableFuture<Void> biRunStage(Executor e, CompletionStage<?> o,
1356 Runnable f) {
1357 CompletableFuture<?> b; Object r, s;
1358 if (f == null || (b = o.toCompletableFuture()) == null)
1359 throw new NullPointerException();
1360 CompletableFuture<Void> d = newIncompleteFuture();
1361 if ((r = result) == null || (s = b.result) == null)
1362 bipush(b, new BiRun<>(e, d, this, b, f));
1363 else if (e == null)
1364 d.biRun(r, s, f, null);
1365 else
1366 try {
1367 e.execute(new BiRun<>(null, d, this, b, f));
1368 } catch (Throwable ex) {
1369 d.result = encodeThrowable(ex);
1370 }
1371 return d;
1372 }
1373
1374 @SuppressWarnings("serial")
1375 static final class BiRelay<T,U> extends BiCompletion<T,U,Void> { // for And
1376 BiRelay(CompletableFuture<Void> dep,
1377 CompletableFuture<T> src, CompletableFuture<U> snd) {
1378 super(null, dep, src, snd);
1379 }
1380 final CompletableFuture<Void> tryFire(int mode) {
1381 CompletableFuture<Void> d;
1382 CompletableFuture<T> a;
1383 CompletableFuture<U> b;
1384 Object r, s, z; Throwable x;
1385 if ((d = dep) == null
1386 || (a = src) == null || (r = a.result) == null
1387 || (b = snd) == null || (s = b.result) == null)
1388 return null;
1389 if (d.result == null) {
1390 if ((r instanceof AltResult
1391 && (x = ((AltResult)(z = r)).ex) != null) ||
1392 (s instanceof AltResult
1393 && (x = ((AltResult)(z = s)).ex) != null))
1394 d.completeThrowable(x, z);
1395 else
1396 d.completeNull();
1397 }
1398 src = null; snd = null; dep = null;
1399 return d.postFire(a, b, mode);
1400 }
1401 }
1402
1403 /** Recursively constructs a tree of completions. */
1404 static CompletableFuture<Void> andTree(CompletableFuture<?>[] cfs,
1405 int lo, int hi) {
1406 CompletableFuture<Void> d = new CompletableFuture<Void>();
1407 if (lo > hi) // empty
1408 d.result = NIL;
1409 else {
1410 CompletableFuture<?> a, b; Object r, s, z; Throwable x;
1411 int mid = (lo + hi) >>> 1;
1412 if ((a = (lo == mid ? cfs[lo] :
1413 andTree(cfs, lo, mid))) == null ||
1414 (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
1415 andTree(cfs, mid+1, hi))) == null)
1416 throw new NullPointerException();
1417 if ((r = a.result) == null || (s = b.result) == null)
1418 a.bipush(b, new BiRelay<>(d, a, b));
1419 else if ((r instanceof AltResult
1420 && (x = ((AltResult)(z = r)).ex) != null) ||
1421 (s instanceof AltResult
1422 && (x = ((AltResult)(z = s)).ex) != null))
1423 d.result = encodeThrowable(x, z);
1424 else
1425 d.result = NIL;
1426 }
1427 return d;
1428 }
1429
1430 /* ------------- Projected (Ored) BiCompletions -------------- */
1431
1432 /**
1433 * Pushes completion to this and b unless either done.
1434 * Caller should first check that result and b.result are both null.
1435 */
1436 final void orpush(CompletableFuture<?> b, BiCompletion<?,?,?> c) {
1437 if (c != null) {
1438 while (!tryPushStack(c)) {
1439 if (result != null) {
1440 NEXT.set(c, null);
1441 break;
1442 }
1443 }
1444 if (result != null)
1445 c.tryFire(SYNC);
1446 else
1447 b.unipush(new CoCompletion(c));
1448 }
1449 }
1450
1451 @SuppressWarnings("serial")
1452 static final class OrApply<T,U extends T,V> extends BiCompletion<T,U,V> {
1453 Function<? super T,? extends V> fn;
1454 OrApply(Executor executor, CompletableFuture<V> dep,
1455 CompletableFuture<T> src, CompletableFuture<U> snd,
1456 Function<? super T,? extends V> fn) {
1457 super(executor, dep, src, snd); this.fn = fn;
1458 }
1459 final CompletableFuture<V> tryFire(int mode) {
1460 CompletableFuture<V> d;
1461 CompletableFuture<T> a;
1462 CompletableFuture<U> b;
1463 Object r; Throwable x; Function<? super T,? extends V> f;
1464 if ((d = dep) == null || (f = fn) == null
1465 || (a = src) == null || (b = snd) == null
1466 || ((r = a.result) == null && (r = b.result) == null))
1467 return null;
1468 tryComplete: if (d.result == null) {
1469 try {
1470 if (mode <= 0 && !claim())
1471 return null;
1472 if (r instanceof AltResult) {
1473 if ((x = ((AltResult)r).ex) != null) {
1474 d.completeThrowable(x, r);
1475 break tryComplete;
1476 }
1477 r = null;
1478 }
1479 @SuppressWarnings("unchecked") T t = (T) r;
1480 d.completeValue(f.apply(t));
1481 } catch (Throwable ex) {
1482 d.completeThrowable(ex);
1483 }
1484 }
1485 dep = null; src = null; snd = null; fn = null;
1486 return d.postFire(a, b, mode);
1487 }
1488 }
1489
1490 private <U extends T,V> CompletableFuture<V> orApplyStage(
1491 Executor e, CompletionStage<U> o, Function<? super T, ? extends V> f) {
1492 CompletableFuture<U> b;
1493 if (f == null || (b = o.toCompletableFuture()) == null)
1494 throw new NullPointerException();
1495
1496 Object r; CompletableFuture<? extends T> z;
1497 if ((r = (z = this).result) != null ||
1498 (r = (z = b).result) != null)
1499 return z.uniApplyNow(r, e, f);
1500
1501 CompletableFuture<V> d = newIncompleteFuture();
1502 orpush(b, new OrApply<T,U,V>(e, d, this, b, f));
1503 return d;
1504 }
1505
1506 @SuppressWarnings("serial")
1507 static final class OrAccept<T,U extends T> extends BiCompletion<T,U,Void> {
1508 Consumer<? super T> fn;
1509 OrAccept(Executor executor, CompletableFuture<Void> dep,
1510 CompletableFuture<T> src, CompletableFuture<U> snd,
1511 Consumer<? super T> fn) {
1512 super(executor, dep, src, snd); this.fn = fn;
1513 }
1514 final CompletableFuture<Void> tryFire(int mode) {
1515 CompletableFuture<Void> d;
1516 CompletableFuture<T> a;
1517 CompletableFuture<U> b;
1518 Object r; Throwable x; Consumer<? super T> f;
1519 if ((d = dep) == null || (f = fn) == null
1520 || (a = src) == null || (b = snd) == null
1521 || ((r = a.result) == null && (r = b.result) == null))
1522 return null;
1523 tryComplete: if (d.result == null) {
1524 try {
1525 if (mode <= 0 && !claim())
1526 return null;
1527 if (r instanceof AltResult) {
1528 if ((x = ((AltResult)r).ex) != null) {
1529 d.completeThrowable(x, r);
1530 break tryComplete;
1531 }
1532 r = null;
1533 }
1534 @SuppressWarnings("unchecked") T t = (T) r;
1535 f.accept(t);
1536 d.completeNull();
1537 } catch (Throwable ex) {
1538 d.completeThrowable(ex);
1539 }
1540 }
1541 dep = null; src = null; snd = null; fn = null;
1542 return d.postFire(a, b, mode);
1543 }
1544 }
1545
1546 private <U extends T> CompletableFuture<Void> orAcceptStage(
1547 Executor e, CompletionStage<U> o, Consumer<? super T> f) {
1548 CompletableFuture<U> b;
1549 if (f == null || (b = o.toCompletableFuture()) == null)
1550 throw new NullPointerException();
1551
1552 Object r; CompletableFuture<? extends T> z;
1553 if ((r = (z = this).result) != null ||
1554 (r = (z = b).result) != null)
1555 return z.uniAcceptNow(r, e, f);
1556
1557 CompletableFuture<Void> d = newIncompleteFuture();
1558 orpush(b, new OrAccept<T,U>(e, d, this, b, f));
1559 return d;
1560 }
1561
1562 @SuppressWarnings("serial")
1563 static final class OrRun<T,U> extends BiCompletion<T,U,Void> {
1564 Runnable fn;
1565 OrRun(Executor executor, CompletableFuture<Void> dep,
1566 CompletableFuture<T> src, CompletableFuture<U> snd,
1567 Runnable fn) {
1568 super(executor, dep, src, snd); this.fn = fn;
1569 }
1570 final CompletableFuture<Void> tryFire(int mode) {
1571 CompletableFuture<Void> d;
1572 CompletableFuture<T> a;
1573 CompletableFuture<U> b;
1574 Object r; Throwable x; Runnable f;
1575 if ((d = dep) == null || (f = fn) == null
1576 || (a = src) == null || (b = snd) == null
1577 || ((r = a.result) == null && (r = b.result) == null))
1578 return null;
1579 if (d.result == null) {
1580 try {
1581 if (mode <= 0 && !claim())
1582 return null;
1583 else if (r instanceof AltResult
1584 && (x = ((AltResult)r).ex) != null)
1585 d.completeThrowable(x, r);
1586 else {
1587 f.run();
1588 d.completeNull();
1589 }
1590 } catch (Throwable ex) {
1591 d.completeThrowable(ex);
1592 }
1593 }
1594 dep = null; src = null; snd = null; fn = null;
1595 return d.postFire(a, b, mode);
1596 }
1597 }
1598
1599 private CompletableFuture<Void> orRunStage(Executor e, CompletionStage<?> o,
1600 Runnable f) {
1601 CompletableFuture<?> b;
1602 if (f == null || (b = o.toCompletableFuture()) == null)
1603 throw new NullPointerException();
1604
1605 Object r; CompletableFuture<?> z;
1606 if ((r = (z = this).result) != null ||
1607 (r = (z = b).result) != null)
1608 return z.uniRunNow(r, e, f);
1609
1610 CompletableFuture<Void> d = newIncompleteFuture();
1611 orpush(b, new OrRun<>(e, d, this, b, f));
1612 return d;
1613 }
1614
1615 /** Completion for an anyOf input future. */
1616 @SuppressWarnings("serial")
1617 static class AnyOf extends Completion {
1618 CompletableFuture<Object> dep; CompletableFuture<?> src;
1619 CompletableFuture<?>[] srcs;
1620 AnyOf(CompletableFuture<Object> dep, CompletableFuture<?> src,
1621 CompletableFuture<?>[] srcs) {
1622 this.dep = dep; this.src = src; this.srcs = srcs;
1623 }
1624 final CompletableFuture<Object> tryFire(int mode) {
1625 // assert mode != ASYNC;
1626 CompletableFuture<Object> d; CompletableFuture<?> a;
1627 CompletableFuture<?>[] as;
1628 Object r;
1629 if ((d = dep) == null
1630 || (a = src) == null || (r = a.result) == null
1631 || (as = srcs) == null)
1632 return null;
1633 dep = null; src = null; srcs = null;
1634 if (d.completeRelay(r)) {
1635 for (CompletableFuture<?> b : as)
1636 if (b != a)
1637 b.cleanStack();
1638 if (mode < 0)
1639 return d;
1640 else
1641 d.postComplete();
1642 }
1643 return null;
1644 }
1645 final boolean isLive() {
1646 CompletableFuture<Object> d;
1647 return (d = dep) != null && d.result == null;
1648 }
1649 }
1650
1651 /* ------------- Zero-input Async forms -------------- */
1652
1653 @SuppressWarnings("serial")
1654 static final class AsyncSupply<T> extends ForkJoinTask<Void>
1655 implements Runnable, AsynchronousCompletionTask {
1656 CompletableFuture<T> dep; Supplier<? extends T> fn;
1657 AsyncSupply(CompletableFuture<T> dep, Supplier<? extends T> fn) {
1658 this.dep = dep; this.fn = fn;
1659 }
1660
1661 public final Void getRawResult() { return null; }
1662 public final void setRawResult(Void v) {}
1663 public final boolean exec() { run(); return false; }
1664
1665 public void run() {
1666 CompletableFuture<T> d; Supplier<? extends T> f;
1667 if ((d = dep) != null && (f = fn) != null) {
1668 dep = null; fn = null;
1669 if (d.result == null) {
1670 try {
1671 d.completeValue(f.get());
1672 } catch (Throwable ex) {
1673 d.completeThrowable(ex);
1674 }
1675 }
1676 d.postComplete();
1677 }
1678 }
1679 }
1680
1681 static <U> CompletableFuture<U> asyncSupplyStage(Executor e,
1682 Supplier<U> f) {
1683 if (f == null) throw new NullPointerException();
1684 CompletableFuture<U> d = new CompletableFuture<U>();
1685 e.execute(new AsyncSupply<U>(d, f));
1686 return d;
1687 }
1688
1689 @SuppressWarnings("serial")
1690 static final class AsyncRun extends ForkJoinTask<Void>
1691 implements Runnable, AsynchronousCompletionTask {
1692 CompletableFuture<Void> dep; Runnable fn;
1693 AsyncRun(CompletableFuture<Void> dep, Runnable fn) {
1694 this.dep = dep; this.fn = fn;
1695 }
1696
1697 public final Void getRawResult() { return null; }
1698 public final void setRawResult(Void v) {}
1699 public final boolean exec() { run(); return false; }
1700
1701 public void run() {
1702 CompletableFuture<Void> d; Runnable f;
1703 if ((d = dep) != null && (f = fn) != null) {
1704 dep = null; fn = null;
1705 if (d.result == null) {
1706 try {
1707 f.run();
1708 d.completeNull();
1709 } catch (Throwable ex) {
1710 d.completeThrowable(ex);
1711 }
1712 }
1713 d.postComplete();
1714 }
1715 }
1716 }
1717
1718 static CompletableFuture<Void> asyncRunStage(Executor e, Runnable f) {
1719 if (f == null) throw new NullPointerException();
1720 CompletableFuture<Void> d = new CompletableFuture<Void>();
1721 e.execute(new AsyncRun(d, f));
1722 return d;
1723 }
1724
1725 /* ------------- Signallers -------------- */
1726
1727 /**
1728 * Completion for recording and releasing a waiting thread. This
1729 * class implements ManagedBlocker to avoid starvation when
1730 * blocking actions pile up in ForkJoinPools.
1731 */
1732 @SuppressWarnings("serial")
1733 static final class Signaller extends Completion
1734 implements ForkJoinPool.ManagedBlocker {
1735 long nanos; // remaining wait time if timed
1736 final long deadline; // non-zero if timed
1737 final boolean interruptible;
1738 boolean interrupted;
1739 volatile Thread thread;
1740
1741 Signaller(boolean interruptible, long nanos, long deadline) {
1742 this.thread = Thread.currentThread();
1743 this.interruptible = interruptible;
1744 this.nanos = nanos;
1745 this.deadline = deadline;
1746 }
1747 final CompletableFuture<?> tryFire(int ignore) {
1748 Thread w; // no need to atomically claim
1749 if ((w = thread) != null) {
1750 thread = null;
1751 LockSupport.unpark(w);
1752 }
1753 return null;
1754 }
1755 public boolean isReleasable() {
1756 if (Thread.interrupted())
1757 interrupted = true;
1758 return ((interrupted && interruptible) ||
1759 (deadline != 0L &&
1760 (nanos <= 0L ||
1761 (nanos = deadline - System.nanoTime()) <= 0L)) ||
1762 thread == null);
1763 }
1764 public boolean block() {
1765 while (!isReleasable()) {
1766 if (deadline == 0L)
1767 LockSupport.park(this);
1768 else
1769 LockSupport.parkNanos(this, nanos);
1770 }
1771 return true;
1772 }
1773 final boolean isLive() { return thread != null; }
1774 }
1775
1776 /**
1777 * Returns raw result after waiting, or null if interruptible and
1778 * interrupted.
1779 */
1780 private Object waitingGet(boolean interruptible) {
1781 Signaller q = null;
1782 boolean queued = false;
1783 Object r;
1784 while ((r = result) == null) {
1785 if (q == null) {
1786 q = new Signaller(interruptible, 0L, 0L);
1787 if (Thread.currentThread() instanceof ForkJoinWorkerThread)
1788 ForkJoinPool.helpAsyncBlocker(defaultExecutor(), q);
1789 }
1790 else if (!queued)
1791 queued = tryPushStack(q);
1792 else {
1793 try {
1794 ForkJoinPool.managedBlock(q);
1795 } catch (InterruptedException ie) { // currently cannot happen
1796 q.interrupted = true;
1797 }
1798 if (q.interrupted && interruptible)
1799 break;
1800 }
1801 }
1802 if (q != null && queued) {
1803 q.thread = null;
1804 if (!interruptible && q.interrupted)
1805 Thread.currentThread().interrupt();
1806 if (r == null)
1807 cleanStack();
1808 }
1809 if (r != null || (r = result) != null)
1810 postComplete();
1811 return r;
1812 }
1813
1814 /**
1815 * Returns raw result after waiting, or null if interrupted, or
1816 * throws TimeoutException on timeout.
1817 */
1818 private Object timedGet(long nanos) throws TimeoutException {
1819 if (Thread.interrupted())
1820 return null;
1821 if (nanos > 0L) {
1822 long d = System.nanoTime() + nanos;
1823 long deadline = (d == 0L) ? 1L : d; // avoid 0
1824 Signaller q = null;
1825 boolean queued = false;
1826 Object r;
1827 while ((r = result) == null) { // similar to untimed
1828 if (q == null) {
1829 q = new Signaller(true, nanos, deadline);
1830 if (Thread.currentThread() instanceof ForkJoinWorkerThread)
1831 ForkJoinPool.helpAsyncBlocker(defaultExecutor(), q);
1832 }
1833 else if (!queued)
1834 queued = tryPushStack(q);
1835 else if (q.nanos <= 0L)
1836 break;
1837 else {
1838 try {
1839 ForkJoinPool.managedBlock(q);
1840 } catch (InterruptedException ie) {
1841 q.interrupted = true;
1842 }
1843 if (q.interrupted)
1844 break;
1845 }
1846 }
1847 if (q != null && queued) {
1848 q.thread = null;
1849 if (r == null)
1850 cleanStack();
1851 }
1852 if (r != null || (r = result) != null)
1853 postComplete();
1854 if (r != null || (q != null && q.interrupted))
1855 return r;
1856 }
1857 throw new TimeoutException();
1858 }
1859
1860 /* ------------- public methods -------------- */
1861
1862 /**
1863 * Creates a new incomplete CompletableFuture.
1864 */
1865 public CompletableFuture() {
1866 }
1867
1868 /**
1869 * Creates a new complete CompletableFuture with given encoded result.
1870 */
1871 CompletableFuture(Object r) {
1872 this.result = r;
1873 }
1874
1875 /**
1876 * Returns a new CompletableFuture that is asynchronously completed
1877 * by a task running in the {@link ForkJoinPool#commonPool()} with
1878 * the value obtained by calling the given Supplier.
1879 *
1880 * @param supplier a function returning the value to be used
1881 * to complete the returned CompletableFuture
1882 * @param <U> the function's return type
1883 * @return the new CompletableFuture
1884 */
1885 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
1886 return asyncSupplyStage(ASYNC_POOL, supplier);
1887 }
1888
1889 /**
1890 * Returns a new CompletableFuture that is asynchronously completed
1891 * by a task running in the given executor with the value obtained
1892 * by calling the given Supplier.
1893 *
1894 * @param supplier a function returning the value to be used
1895 * to complete the returned CompletableFuture
1896 * @param executor the executor to use for asynchronous execution
1897 * @param <U> the function's return type
1898 * @return the new CompletableFuture
1899 */
1900 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
1901 Executor executor) {
1902 return asyncSupplyStage(screenExecutor(executor), supplier);
1903 }
1904
1905 /**
1906 * Returns a new CompletableFuture that is asynchronously completed
1907 * by a task running in the {@link ForkJoinPool#commonPool()} after
1908 * it runs the given action.
1909 *
1910 * @param runnable the action to run before completing the
1911 * returned CompletableFuture
1912 * @return the new CompletableFuture
1913 */
1914 public static CompletableFuture<Void> runAsync(Runnable runnable) {
1915 return asyncRunStage(ASYNC_POOL, runnable);
1916 }
1917
1918 /**
1919 * Returns a new CompletableFuture that is asynchronously completed
1920 * by a task running in the given executor after it runs the given
1921 * action.
1922 *
1923 * @param runnable the action to run before completing the
1924 * returned CompletableFuture
1925 * @param executor the executor to use for asynchronous execution
1926 * @return the new CompletableFuture
1927 */
1928 public static CompletableFuture<Void> runAsync(Runnable runnable,
1929 Executor executor) {
1930 return asyncRunStage(screenExecutor(executor), runnable);
1931 }
1932
1933 /**
1934 * Returns a new CompletableFuture that is already completed with
1935 * the given value.
1936 *
1937 * @param value the value
1938 * @param <U> the type of the value
1939 * @return the completed CompletableFuture
1940 */
1941 public static <U> CompletableFuture<U> completedFuture(U value) {
1942 return new CompletableFuture<U>((value == null) ? NIL : value);
1943 }
1944
1945 /**
1946 * Returns {@code true} if completed in any fashion: normally,
1947 * exceptionally, or via cancellation.
1948 *
1949 * @return {@code true} if completed
1950 */
1951 public boolean isDone() {
1952 return result != null;
1953 }
1954
1955 /**
1956 * Waits if necessary for this future to complete, and then
1957 * returns its result.
1958 *
1959 * @return the result value
1960 * @throws CancellationException if this future was cancelled
1961 * @throws ExecutionException if this future completed exceptionally
1962 * @throws InterruptedException if the current thread was interrupted
1963 * while waiting
1964 */
1965 @SuppressWarnings("unchecked")
1966 public T get() throws InterruptedException, ExecutionException {
1967 Object r;
1968 if ((r = result) == null)
1969 r = waitingGet(true);
1970 return (T) reportGet(r);
1971 }
1972
1973 /**
1974 * Waits if necessary for at most the given time for this future
1975 * to complete, and then returns its result, if available.
1976 *
1977 * @param timeout the maximum time to wait
1978 * @param unit the time unit of the timeout argument
1979 * @return the result value
1980 * @throws CancellationException if this future was cancelled
1981 * @throws ExecutionException if this future completed exceptionally
1982 * @throws InterruptedException if the current thread was interrupted
1983 * while waiting
1984 * @throws TimeoutException if the wait timed out
1985 */
1986 @SuppressWarnings("unchecked")
1987 public T get(long timeout, TimeUnit unit)
1988 throws InterruptedException, ExecutionException, TimeoutException {
1989 long nanos = unit.toNanos(timeout);
1990 Object r;
1991 if ((r = result) == null)
1992 r = timedGet(nanos);
1993 return (T) reportGet(r);
1994 }
1995
1996 /**
1997 * Returns the result value when complete, or throws an
1998 * (unchecked) exception if completed exceptionally. To better
1999 * conform with the use of common functional forms, if a
2000 * computation involved in the completion of this
2001 * CompletableFuture threw an exception, this method throws an
2002 * (unchecked) {@link CompletionException} with the underlying
2003 * exception as its cause.
2004 *
2005 * @return the result value
2006 * @throws CancellationException if the computation was cancelled
2007 * @throws CompletionException if this future completed
2008 * exceptionally or a completion computation threw an exception
2009 */
2010 @SuppressWarnings("unchecked")
2011 public T join() {
2012 Object r;
2013 if ((r = result) == null)
2014 r = waitingGet(false);
2015 return (T) reportJoin(r);
2016 }
2017
2018 /**
2019 * Returns the result value (or throws any encountered exception)
2020 * if completed, else returns the given valueIfAbsent.
2021 *
2022 * @param valueIfAbsent the value to return if not completed
2023 * @return the result value, if completed, else the given valueIfAbsent
2024 * @throws CancellationException if the computation was cancelled
2025 * @throws CompletionException if this future completed
2026 * exceptionally or a completion computation threw an exception
2027 */
2028 @SuppressWarnings("unchecked")
2029 public T getNow(T valueIfAbsent) {
2030 Object r;
2031 return ((r = result) == null) ? valueIfAbsent : (T) reportJoin(r);
2032 }
2033
2034 /**
2035 * If not already completed, sets the value returned by {@link
2036 * #get()} and related methods to the given value.
2037 *
2038 * @param value the result value
2039 * @return {@code true} if this invocation caused this CompletableFuture
2040 * to transition to a completed state, else {@code false}
2041 */
2042 public boolean complete(T value) {
2043 boolean triggered = completeValue(value);
2044 postComplete();
2045 return triggered;
2046 }
2047
2048 /**
2049 * If not already completed, causes invocations of {@link #get()}
2050 * and related methods to throw the given exception.
2051 *
2052 * @param ex the exception
2053 * @return {@code true} if this invocation caused this CompletableFuture
2054 * to transition to a completed state, else {@code false}
2055 */
2056 public boolean completeExceptionally(Throwable ex) {
2057 if (ex == null) throw new NullPointerException();
2058 boolean triggered = internalComplete(new AltResult(ex));
2059 postComplete();
2060 return triggered;
2061 }
2062
2063 public <U> CompletableFuture<U> thenApply(
2064 Function<? super T,? extends U> fn) {
2065 return uniApplyStage(null, fn);
2066 }
2067
2068 public <U> CompletableFuture<U> thenApplyAsync(
2069 Function<? super T,? extends U> fn) {
2070 return uniApplyStage(defaultExecutor(), fn);
2071 }
2072
2073 public <U> CompletableFuture<U> thenApplyAsync(
2074 Function<? super T,? extends U> fn, Executor executor) {
2075 return uniApplyStage(screenExecutor(executor), fn);
2076 }
2077
2078 public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
2079 return uniAcceptStage(null, action);
2080 }
2081
2082 public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
2083 return uniAcceptStage(defaultExecutor(), action);
2084 }
2085
2086 public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
2087 Executor executor) {
2088 return uniAcceptStage(screenExecutor(executor), action);
2089 }
2090
2091 public CompletableFuture<Void> thenRun(Runnable action) {
2092 return uniRunStage(null, action);
2093 }
2094
2095 public CompletableFuture<Void> thenRunAsync(Runnable action) {
2096 return uniRunStage(defaultExecutor(), action);
2097 }
2098
2099 public CompletableFuture<Void> thenRunAsync(Runnable action,
2100 Executor executor) {
2101 return uniRunStage(screenExecutor(executor), action);
2102 }
2103
2104 public <U,V> CompletableFuture<V> thenCombine(
2105 CompletionStage<? extends U> other,
2106 BiFunction<? super T,? super U,? extends V> fn) {
2107 return biApplyStage(null, other, fn);
2108 }
2109
2110 public <U,V> CompletableFuture<V> thenCombineAsync(
2111 CompletionStage<? extends U> other,
2112 BiFunction<? super T,? super U,? extends V> fn) {
2113 return biApplyStage(defaultExecutor(), other, fn);
2114 }
2115
2116 public <U,V> CompletableFuture<V> thenCombineAsync(
2117 CompletionStage<? extends U> other,
2118 BiFunction<? super T,? super U,? extends V> fn, Executor executor) {
2119 return biApplyStage(screenExecutor(executor), other, fn);
2120 }
2121
2122 public <U> CompletableFuture<Void> thenAcceptBoth(
2123 CompletionStage<? extends U> other,
2124 BiConsumer<? super T, ? super U> action) {
2125 return biAcceptStage(null, other, action);
2126 }
2127
2128 public <U> CompletableFuture<Void> thenAcceptBothAsync(
2129 CompletionStage<? extends U> other,
2130 BiConsumer<? super T, ? super U> action) {
2131 return biAcceptStage(defaultExecutor(), other, action);
2132 }
2133
2134 public <U> CompletableFuture<Void> thenAcceptBothAsync(
2135 CompletionStage<? extends U> other,
2136 BiConsumer<? super T, ? super U> action, Executor executor) {
2137 return biAcceptStage(screenExecutor(executor), other, action);
2138 }
2139
2140 public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,
2141 Runnable action) {
2142 return biRunStage(null, other, action);
2143 }
2144
2145 public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
2146 Runnable action) {
2147 return biRunStage(defaultExecutor(), other, action);
2148 }
2149
2150 public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
2151 Runnable action,
2152 Executor executor) {
2153 return biRunStage(screenExecutor(executor), other, action);
2154 }
2155
2156 public <U> CompletableFuture<U> applyToEither(
2157 CompletionStage<? extends T> other, Function<? super T, U> fn) {
2158 return orApplyStage(null, other, fn);
2159 }
2160
2161 public <U> CompletableFuture<U> applyToEitherAsync(
2162 CompletionStage<? extends T> other, Function<? super T, U> fn) {
2163 return orApplyStage(defaultExecutor(), other, fn);
2164 }
2165
2166 public <U> CompletableFuture<U> applyToEitherAsync(
2167 CompletionStage<? extends T> other, Function<? super T, U> fn,
2168 Executor executor) {
2169 return orApplyStage(screenExecutor(executor), other, fn);
2170 }
2171
2172 public CompletableFuture<Void> acceptEither(
2173 CompletionStage<? extends T> other, Consumer<? super T> action) {
2174 return orAcceptStage(null, other, action);
2175 }
2176
2177 public CompletableFuture<Void> acceptEitherAsync(
2178 CompletionStage<? extends T> other, Consumer<? super T> action) {
2179 return orAcceptStage(defaultExecutor(), other, action);
2180 }
2181
2182 public CompletableFuture<Void> acceptEitherAsync(
2183 CompletionStage<? extends T> other, Consumer<? super T> action,
2184 Executor executor) {
2185 return orAcceptStage(screenExecutor(executor), other, action);
2186 }
2187
2188 public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,
2189 Runnable action) {
2190 return orRunStage(null, other, action);
2191 }
2192
2193 public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
2194 Runnable action) {
2195 return orRunStage(defaultExecutor(), other, action);
2196 }
2197
2198 public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
2199 Runnable action,
2200 Executor executor) {
2201 return orRunStage(screenExecutor(executor), other, action);
2202 }
2203
2204 public <U> CompletableFuture<U> thenCompose(
2205 Function<? super T, ? extends CompletionStage<U>> fn) {
2206 return uniComposeStage(null, fn);
2207 }
2208
2209 public <U> CompletableFuture<U> thenComposeAsync(
2210 Function<? super T, ? extends CompletionStage<U>> fn) {
2211 return uniComposeStage(defaultExecutor(), fn);
2212 }
2213
2214 public <U> CompletableFuture<U> thenComposeAsync(
2215 Function<? super T, ? extends CompletionStage<U>> fn,
2216 Executor executor) {
2217 return uniComposeStage(screenExecutor(executor), fn);
2218 }
2219
2220 public CompletableFuture<T> whenComplete(
2221 BiConsumer<? super T, ? super Throwable> action) {
2222 return uniWhenCompleteStage(null, action);
2223 }
2224
2225 public CompletableFuture<T> whenCompleteAsync(
2226 BiConsumer<? super T, ? super Throwable> action) {
2227 return uniWhenCompleteStage(defaultExecutor(), action);
2228 }
2229
2230 public CompletableFuture<T> whenCompleteAsync(
2231 BiConsumer<? super T, ? super Throwable> action, Executor executor) {
2232 return uniWhenCompleteStage(screenExecutor(executor), action);
2233 }
2234
2235 public <U> CompletableFuture<U> handle(
2236 BiFunction<? super T, Throwable, ? extends U> fn) {
2237 return uniHandleStage(null, fn);
2238 }
2239
2240 public <U> CompletableFuture<U> handleAsync(
2241 BiFunction<? super T, Throwable, ? extends U> fn) {
2242 return uniHandleStage(defaultExecutor(), fn);
2243 }
2244
2245 public <U> CompletableFuture<U> handleAsync(
2246 BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) {
2247 return uniHandleStage(screenExecutor(executor), fn);
2248 }
2249
2250 /**
2251 * Returns this CompletableFuture.
2252 *
2253 * @return this CompletableFuture
2254 */
2255 public CompletableFuture<T> toCompletableFuture() {
2256 return this;
2257 }
2258
2259 // not in interface CompletionStage
2260
2261 /**
2262 * Returns a new CompletableFuture that is completed when this
2263 * CompletableFuture completes, with the result of the given
2264 * function of the exception triggering this CompletableFuture's
2265 * completion when it completes exceptionally; otherwise, if this
2266 * CompletableFuture completes normally, then the returned
2267 * CompletableFuture also completes normally with the same value.
2268 * Note: More flexible versions of this functionality are
2269 * available using methods {@code whenComplete} and {@code handle}.
2270 *
2271 * @param fn the function to use to compute the value of the
2272 * returned CompletableFuture if this CompletableFuture completed
2273 * exceptionally
2274 * @return the new CompletableFuture
2275 */
2276 public CompletableFuture<T> exceptionally(
2277 Function<Throwable, ? extends T> fn) {
2278 return uniExceptionallyStage(fn);
2279 }
2280
2281
2282 /* ------------- Arbitrary-arity constructions -------------- */
2283
2284 /**
2285 * Returns a new CompletableFuture that is completed when all of
2286 * the given CompletableFutures complete. If any of the given
2287 * CompletableFutures complete exceptionally, then the returned
2288 * CompletableFuture also does so, with a CompletionException
2289 * holding this exception as its cause. Otherwise, the results,
2290 * if any, of the given CompletableFutures are not reflected in
2291 * the returned CompletableFuture, but may be obtained by
2292 * inspecting them individually. If no CompletableFutures are
2293 * provided, returns a CompletableFuture completed with the value
2294 * {@code null}.
2295 *
2296 * <p>Among the applications of this method is to await completion
2297 * of a set of independent CompletableFutures before continuing a
2298 * program, as in: {@code CompletableFuture.allOf(c1, c2,
2299 * c3).join();}.
2300 *
2301 * @param cfs the CompletableFutures
2302 * @return a new CompletableFuture that is completed when all of the
2303 * given CompletableFutures complete
2304 * @throws NullPointerException if the array or any of its elements are
2305 * {@code null}
2306 */
2307 public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
2308 return andTree(cfs, 0, cfs.length - 1);
2309 }
2310
2311 /**
2312 * Returns a new CompletableFuture that is completed when any of
2313 * the given CompletableFutures complete, with the same result.
2314 * Otherwise, if it completed exceptionally, the returned
2315 * CompletableFuture also does so, with a CompletionException
2316 * holding this exception as its cause. If no CompletableFutures
2317 * are provided, returns an incomplete CompletableFuture.
2318 *
2319 * @param cfs the CompletableFutures
2320 * @return a new CompletableFuture that is completed with the
2321 * result or exception of any of the given CompletableFutures when
2322 * one completes
2323 * @throws NullPointerException if the array or any of its elements are
2324 * {@code null}
2325 */
2326 public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
2327 int n; Object r;
2328 if ((n = cfs.length) <= 1)
2329 return (n == 0)
2330 ? new CompletableFuture<Object>()
2331 : uniCopyStage(cfs[0]);
2332 for (CompletableFuture<?> cf : cfs)
2333 if ((r = cf.result) != null)
2334 return new CompletableFuture<Object>(encodeRelay(r));
2335 cfs = cfs.clone();
2336 CompletableFuture<Object> d = new CompletableFuture<>();
2337 for (CompletableFuture<?> cf : cfs)
2338 cf.unipush(new AnyOf(d, cf, cfs));
2339 // If d was completed while we were adding completions, we should
2340 // clean the stack of any sources that may have had completions
2341 // pushed on their stack after d was completed.
2342 if (d.result != null)
2343 for (int i = 0, len = cfs.length; i < len; i++)
2344 if (cfs[i].result != null)
2345 for (i++; i < len; i++)
2346 if (cfs[i].result == null)
2347 cfs[i].cleanStack();
2348 return d;
2349 }
2350
2351 /* ------------- Control and status methods -------------- */
2352
2353 /**
2354 * If not already completed, completes this CompletableFuture with
2355 * a {@link CancellationException}. Dependent CompletableFutures
2356 * that have not already completed will also complete
2357 * exceptionally, with a {@link CompletionException} caused by
2358 * this {@code CancellationException}.
2359 *
2360 * @param mayInterruptIfRunning this value has no effect in this
2361 * implementation because interrupts are not used to control
2362 * processing.
2363 *
2364 * @return {@code true} if this task is now cancelled
2365 */
2366 public boolean cancel(boolean mayInterruptIfRunning) {
2367 boolean cancelled = (result == null) &&
2368 internalComplete(new AltResult(new CancellationException()));
2369 postComplete();
2370 return cancelled || isCancelled();
2371 }
2372
2373 /**
2374 * Returns {@code true} if this CompletableFuture was cancelled
2375 * before it completed normally.
2376 *
2377 * @return {@code true} if this CompletableFuture was cancelled
2378 * before it completed normally
2379 */
2380 public boolean isCancelled() {
2381 Object r;
2382 return ((r = result) instanceof AltResult) &&
2383 (((AltResult)r).ex instanceof CancellationException);
2384 }
2385
2386 /**
2387 * Returns {@code true} if this CompletableFuture completed
2388 * exceptionally, in any way. Possible causes include
2389 * cancellation, explicit invocation of {@code
2390 * completeExceptionally}, and abrupt termination of a
2391 * CompletionStage action.
2392 *
2393 * @return {@code true} if this CompletableFuture completed
2394 * exceptionally
2395 */
2396 public boolean isCompletedExceptionally() {
2397 Object r;
2398 return ((r = result) instanceof AltResult) && r != NIL;
2399 }
2400
2401 /**
2402 * Forcibly sets or resets the value subsequently returned by
2403 * method {@link #get()} and related methods, whether or not
2404 * already completed. This method is designed for use only in
2405 * error recovery actions, and even in such situations may result
2406 * in ongoing dependent completions using established versus
2407 * overwritten outcomes.
2408 *
2409 * @param value the completion value
2410 */
2411 public void obtrudeValue(T value) {
2412 result = (value == null) ? NIL : value;
2413 postComplete();
2414 }
2415
2416 /**
2417 * Forcibly causes subsequent invocations of method {@link #get()}
2418 * and related methods to throw the given exception, whether or
2419 * not already completed. This method is designed for use only in
2420 * error recovery actions, and even in such situations may result
2421 * in ongoing dependent completions using established versus
2422 * overwritten outcomes.
2423 *
2424 * @param ex the exception
2425 * @throws NullPointerException if the exception is null
2426 */
2427 public void obtrudeException(Throwable ex) {
2428 if (ex == null) throw new NullPointerException();
2429 result = new AltResult(ex);
2430 postComplete();
2431 }
2432
2433 /**
2434 * Returns the estimated number of CompletableFutures whose
2435 * completions are awaiting completion of this CompletableFuture.
2436 * This method is designed for use in monitoring system state, not
2437 * for synchronization control.
2438 *
2439 * @return the number of dependent CompletableFutures
2440 */
2441 public int getNumberOfDependents() {
2442 int count = 0;
2443 for (Completion p = stack; p != null; p = p.next)
2444 ++count;
2445 return count;
2446 }
2447
2448 /**
2449 * Returns a string identifying this CompletableFuture, as well as
2450 * its completion state. The state, in brackets, contains the
2451 * String {@code "Completed Normally"} or the String {@code
2452 * "Completed Exceptionally"}, or the String {@code "Not
2453 * completed"} followed by the number of CompletableFutures
2454 * dependent upon its completion, if any.
2455 *
2456 * @return a string identifying this CompletableFuture, as well as its state
2457 */
2458 public String toString() {
2459 Object r = result;
2460 int count = 0; // avoid call to getNumberOfDependents in case disabled
2461 for (Completion p = stack; p != null; p = p.next)
2462 ++count;
2463 return super.toString() +
2464 ((r == null) ?
2465 ((count == 0) ?
2466 "[Not completed]" :
2467 "[Not completed, " + count + " dependents]") :
2468 (((r instanceof AltResult) && ((AltResult)r).ex != null) ?
2469 "[Completed exceptionally]" :
2470 "[Completed normally]"));
2471 }
2472
2473 // jdk9 additions
2474
2475 /**
2476 * Returns a new incomplete CompletableFuture of the type to be
2477 * returned by a CompletionStage method. Subclasses should
2478 * normally override this method to return an instance of the same
2479 * class as this CompletableFuture. The default implementation
2480 * returns an instance of class CompletableFuture.
2481 *
2482 * @param <U> the type of the value
2483 * @return a new CompletableFuture
2484 * @since 9
2485 */
2486 public <U> CompletableFuture<U> newIncompleteFuture() {
2487 return new CompletableFuture<U>();
2488 }
2489
2490 /**
2491 * Returns the default Executor used for async methods that do not
2492 * specify an Executor. This class uses the {@link
2493 * ForkJoinPool#commonPool()} if it supports more than one
2494 * parallel thread, or else an Executor using one thread per async
2495 * task. This method may be overridden in subclasses to return
2496 * an Executor that provides at least one independent thread.
2497 *
2498 * @return the executor
2499 * @since 9
2500 */
2501 public Executor defaultExecutor() {
2502 return ASYNC_POOL;
2503 }
2504
2505 /**
2506 * Returns a new CompletableFuture that is completed normally with
2507 * the same value as this CompletableFuture when it completes
2508 * normally. If this CompletableFuture completes exceptionally,
2509 * then the returned CompletableFuture completes exceptionally
2510 * with a CompletionException with this exception as cause. The
2511 * behavior is equivalent to {@code thenApply(x -> x)}. This
2512 * method may be useful as a form of "defensive copying", to
2513 * prevent clients from completing, while still being able to
2514 * arrange dependent actions.
2515 *
2516 * @return the new CompletableFuture
2517 * @since 9
2518 */
2519 public CompletableFuture<T> copy() {
2520 return uniCopyStage(this);
2521 }
2522
2523 /**
2524 * Returns a new CompletionStage that is completed normally with
2525 * the same value as this CompletableFuture when it completes
2526 * normally, and cannot be independently completed or otherwise
2527 * used in ways not defined by the methods of interface {@link
2528 * CompletionStage}. If this CompletableFuture completes
2529 * exceptionally, then the returned CompletionStage completes
2530 * exceptionally with a CompletionException with this exception as
2531 * cause.
2532 *
2533 * @return the new CompletionStage
2534 * @since 9
2535 */
2536 public CompletionStage<T> minimalCompletionStage() {
2537 return uniAsMinimalStage();
2538 }
2539
2540 /**
2541 * Completes this CompletableFuture with the result of
2542 * the given Supplier function invoked from an asynchronous
2543 * task using the given executor.
2544 *
2545 * @param supplier a function returning the value to be used
2546 * to complete this CompletableFuture
2547 * @param executor the executor to use for asynchronous execution
2548 * @return this CompletableFuture
2549 * @since 9
2550 */
2551 public CompletableFuture<T> completeAsync(Supplier<? extends T> supplier,
2552 Executor executor) {
2553 if (supplier == null || executor == null)
2554 throw new NullPointerException();
2555 executor.execute(new AsyncSupply<T>(this, supplier));
2556 return this;
2557 }
2558
2559 /**
2560 * Completes this CompletableFuture with the result of the given
2561 * Supplier function invoked from an asynchronous task using the
2562 * default executor.
2563 *
2564 * @param supplier a function returning the value to be used
2565 * to complete this CompletableFuture
2566 * @return this CompletableFuture
2567 * @since 9
2568 */
2569 public CompletableFuture<T> completeAsync(Supplier<? extends T> supplier) {
2570 return completeAsync(supplier, defaultExecutor());
2571 }
2572
2573 /**
2574 * Exceptionally completes this CompletableFuture with
2575 * a {@link TimeoutException} if not otherwise completed
2576 * before the given timeout.
2577 *
2578 * @param timeout how long to wait before completing exceptionally
2579 * with a TimeoutException, in units of {@code unit}
2580 * @param unit a {@code TimeUnit} determining how to interpret the
2581 * {@code timeout} parameter
2582 * @return this CompletableFuture
2583 * @since 9
2584 */
2585 public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit) {
2586 if (unit == null)
2587 throw new NullPointerException();
2588 if (result == null)
2589 whenComplete(new Canceller(Delayer.delay(new Timeout(this),
2590 timeout, unit)));
2591 return this;
2592 }
2593
2594 /**
2595 * Completes this CompletableFuture with the given value if not
2596 * otherwise completed before the given timeout.
2597 *
2598 * @param value the value to use upon timeout
2599 * @param timeout how long to wait before completing normally
2600 * with the given value, in units of {@code unit}
2601 * @param unit a {@code TimeUnit} determining how to interpret the
2602 * {@code timeout} parameter
2603 * @return this CompletableFuture
2604 * @since 9
2605 */
2606 public CompletableFuture<T> completeOnTimeout(T value, long timeout,
2607 TimeUnit unit) {
2608 if (unit == null)
2609 throw new NullPointerException();
2610 if (result == null)
2611 whenComplete(new Canceller(Delayer.delay(
2612 new DelayedCompleter<T>(this, value),
2613 timeout, unit)));
2614 return this;
2615 }
2616
2617 /**
2618 * Returns a new Executor that submits a task to the given base
2619 * executor after the given delay (or no delay if non-positive).
2620 * Each delay commences upon invocation of the returned executor's
2621 * {@code execute} method.
2622 *
2623 * @param delay how long to delay, in units of {@code unit}
2624 * @param unit a {@code TimeUnit} determining how to interpret the
2625 * {@code delay} parameter
2626 * @param executor the base executor
2627 * @return the new delayed executor
2628 * @since 9
2629 */
2630 public static Executor delayedExecutor(long delay, TimeUnit unit,
2631 Executor executor) {
2632 if (unit == null || executor == null)
2633 throw new NullPointerException();
2634 return new DelayedExecutor(delay, unit, executor);
2635 }
2636
2637 /**
2638 * Returns a new Executor that submits a task to the default
2639 * executor after the given delay (or no delay if non-positive).
2640 * Each delay commences upon invocation of the returned executor's
2641 * {@code execute} method.
2642 *
2643 * @param delay how long to delay, in units of {@code unit}
2644 * @param unit a {@code TimeUnit} determining how to interpret the
2645 * {@code delay} parameter
2646 * @return the new delayed executor
2647 * @since 9
2648 */
2649 public static Executor delayedExecutor(long delay, TimeUnit unit) {
2650 if (unit == null)
2651 throw new NullPointerException();
2652 return new DelayedExecutor(delay, unit, ASYNC_POOL);
2653 }
2654
2655 /**
2656 * Returns a new CompletionStage that is already completed with
2657 * the given value and supports only those methods in
2658 * interface {@link CompletionStage}.
2659 *
2660 * @param value the value
2661 * @param <U> the type of the value
2662 * @return the completed CompletionStage
2663 * @since 9
2664 */
2665 public static <U> CompletionStage<U> completedStage(U value) {
2666 return new MinimalStage<U>((value == null) ? NIL : value);
2667 }
2668
2669 /**
2670 * Returns a new CompletableFuture that is already completed
2671 * exceptionally with the given exception.
2672 *
2673 * @param ex the exception
2674 * @param <U> the type of the value
2675 * @return the exceptionally completed CompletableFuture
2676 * @since 9
2677 */
2678 public static <U> CompletableFuture<U> failedFuture(Throwable ex) {
2679 if (ex == null) throw new NullPointerException();
2680 return new CompletableFuture<U>(new AltResult(ex));
2681 }
2682
2683 /**
2684 * Returns a new CompletionStage that is already completed
2685 * exceptionally with the given exception and supports only those
2686 * methods in interface {@link CompletionStage}.
2687 *
2688 * @param ex the exception
2689 * @param <U> the type of the value
2690 * @return the exceptionally completed CompletionStage
2691 * @since 9
2692 */
2693 public static <U> CompletionStage<U> failedStage(Throwable ex) {
2694 if (ex == null) throw new NullPointerException();
2695 return new MinimalStage<U>(new AltResult(ex));
2696 }
2697
2698 /**
2699 * Singleton delay scheduler, used only for starting and
2700 * cancelling tasks.
2701 */
2702 static final class Delayer {
2703 static ScheduledFuture<?> delay(Runnable command, long delay,
2704 TimeUnit unit) {
2705 return delayer.schedule(command, delay, unit);
2706 }
2707
2708 static final class DaemonThreadFactory implements ThreadFactory {
2709 public Thread newThread(Runnable r) {
2710 Thread t = new Thread(r);
2711 t.setDaemon(true);
2712 t.setName("CompletableFutureDelayScheduler");
2713 return t;
2714 }
2715 }
2716
2717 static final ScheduledThreadPoolExecutor delayer;
2718 static {
2719 (delayer = new ScheduledThreadPoolExecutor(
2720 1, new DaemonThreadFactory())).
2721 setRemoveOnCancelPolicy(true);
2722 }
2723 }
2724
2725 // Little class-ified lambdas to better support monitoring
2726
2727 static final class DelayedExecutor implements Executor {
2728 final long delay;
2729 final TimeUnit unit;
2730 final Executor executor;
2731 DelayedExecutor(long delay, TimeUnit unit, Executor executor) {
2732 this.delay = delay; this.unit = unit; this.executor = executor;
2733 }
2734 public void execute(Runnable r) {
2735 Delayer.delay(new TaskSubmitter(executor, r), delay, unit);
2736 }
2737 }
2738
2739 /** Action to submit user task */
2740 static final class TaskSubmitter implements Runnable {
2741 final Executor executor;
2742 final Runnable action;
2743 TaskSubmitter(Executor executor, Runnable action) {
2744 this.executor = executor;
2745 this.action = action;
2746 }
2747 public void run() { executor.execute(action); }
2748 }
2749
2750 /** Action to completeExceptionally on timeout */
2751 static final class Timeout implements Runnable {
2752 final CompletableFuture<?> f;
2753 Timeout(CompletableFuture<?> f) { this.f = f; }
2754 public void run() {
2755 if (f != null && !f.isDone())
2756 f.completeExceptionally(new TimeoutException());
2757 }
2758 }
2759
2760 /** Action to complete on timeout */
2761 static final class DelayedCompleter<U> implements Runnable {
2762 final CompletableFuture<U> f;
2763 final U u;
2764 DelayedCompleter(CompletableFuture<U> f, U u) { this.f = f; this.u = u; }
2765 public void run() {
2766 if (f != null)
2767 f.complete(u);
2768 }
2769 }
2770
2771 /** Action to cancel unneeded timeouts */
2772 static final class Canceller implements BiConsumer<Object, Throwable> {
2773 final Future<?> f;
2774 Canceller(Future<?> f) { this.f = f; }
2775 public void accept(Object ignore, Throwable ex) {
2776 if (ex == null && f != null && !f.isDone())
2777 f.cancel(false);
2778 }
2779 }
2780
2781 /**
2782 * A subclass that just throws UOE for most non-CompletionStage methods.
2783 */
2784 static final class MinimalStage<T> extends CompletableFuture<T> {
2785 MinimalStage() { }
2786 MinimalStage(Object r) { super(r); }
2787 @Override public <U> CompletableFuture<U> newIncompleteFuture() {
2788 return new MinimalStage<U>(); }
2789 @Override public T get() {
2790 throw new UnsupportedOperationException(); }
2791 @Override public T get(long timeout, TimeUnit unit) {
2792 throw new UnsupportedOperationException(); }
2793 @Override public T getNow(T valueIfAbsent) {
2794 throw new UnsupportedOperationException(); }
2795 @Override public T join() {
2796 throw new UnsupportedOperationException(); }
2797 @Override public boolean complete(T value) {
2798 throw new UnsupportedOperationException(); }
2799 @Override public boolean completeExceptionally(Throwable ex) {
2800 throw new UnsupportedOperationException(); }
2801 @Override public boolean cancel(boolean mayInterruptIfRunning) {
2802 throw new UnsupportedOperationException(); }
2803 @Override public void obtrudeValue(T value) {
2804 throw new UnsupportedOperationException(); }
2805 @Override public void obtrudeException(Throwable ex) {
2806 throw new UnsupportedOperationException(); }
2807 @Override public boolean isDone() {
2808 throw new UnsupportedOperationException(); }
2809 @Override public boolean isCancelled() {
2810 throw new UnsupportedOperationException(); }
2811 @Override public boolean isCompletedExceptionally() {
2812 throw new UnsupportedOperationException(); }
2813 @Override public int getNumberOfDependents() {
2814 throw new UnsupportedOperationException(); }
2815 @Override public CompletableFuture<T> completeAsync
2816 (Supplier<? extends T> supplier, Executor executor) {
2817 throw new UnsupportedOperationException(); }
2818 @Override public CompletableFuture<T> completeAsync
2819 (Supplier<? extends T> supplier) {
2820 throw new UnsupportedOperationException(); }
2821 @Override public CompletableFuture<T> orTimeout
2822 (long timeout, TimeUnit unit) {
2823 throw new UnsupportedOperationException(); }
2824 @Override public CompletableFuture<T> completeOnTimeout
2825 (T value, long timeout, TimeUnit unit) {
2826 throw new UnsupportedOperationException(); }
2827 }
2828
2829 // VarHandle mechanics
2830 private static final VarHandle RESULT;
2831 private static final VarHandle STACK;
2832 private static final VarHandle NEXT;
2833 static {
2834 try {
2835 MethodHandles.Lookup l = MethodHandles.lookup();
2836 RESULT = l.findVarHandle(CompletableFuture.class, "result", Object.class);
2837 STACK = l.findVarHandle(CompletableFuture.class, "stack", Completion.class);
2838 NEXT = l.findVarHandle(Completion.class, "next", Completion.class);
2839 } catch (ReflectiveOperationException e) {
2840 throw new Error(e);
2841 }
2842
2843 // Reduce the risk of rare disastrous classloading in first call to
2844 // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
2845 Class<?> ensureLoaded = LockSupport.class;
2846 }
2847 }