ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.218
Committed: Mon Sep 24 00:20:46 2018 UTC (5 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.217: +21 -12 lines
Log Message:
sadly revert (for consistency with thenCompose): optimize uniComposeExceptionallyStage

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.weakCompareAndSet(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.weakCompareAndSet(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(Executor executor,
932 CompletableFuture<T> dep, CompletableFuture<T> src,
933 Function<? super Throwable, ? extends T> fn) {
934 super(executor, dep, src); this.fn = fn;
935 }
936 final CompletableFuture<T> tryFire(int mode) {
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, mode > 0 ? null : 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 (c != null && !c.claim())
955 return false;
956 if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
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 Executor e, 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>(e, d, this, f));
974 else if (e == null)
975 d.uniExceptionally(r, f, null);
976 else {
977 try {
978 e.execute(new UniExceptionally<T>(null, d, this, f));
979 } catch (Throwable ex) {
980 d.result = encodeThrowable(ex);
981 }
982 }
983 return d;
984 }
985
986 @SuppressWarnings("serial")
987 static final class UniComposeExceptionally<T> extends UniCompletion<T,T> {
988 Function<Throwable, ? extends CompletionStage<T>> fn;
989 UniComposeExceptionally(Executor executor, CompletableFuture<T> dep,
990 CompletableFuture<T> src,
991 Function<Throwable, ? extends CompletionStage<T>> fn) {
992 super(executor, dep, src); this.fn = fn;
993 }
994 final CompletableFuture<T> tryFire(int mode) {
995 CompletableFuture<T> d; CompletableFuture<T> a;
996 Function<Throwable, ? extends CompletionStage<T>> f;
997 Object r; Throwable x;
998 if ((d = dep) == null || (f = fn) == null
999 || (a = src) == null || (r = a.result) == null)
1000 return null;
1001 if (d.result == null) {
1002 if ((r instanceof AltResult) &&
1003 (x = ((AltResult)r).ex) != null) {
1004 try {
1005 if (mode <= 0 && !claim())
1006 return null;
1007 CompletableFuture<T> g = f.apply(x).toCompletableFuture();
1008 if ((r = g.result) != null)
1009 d.completeRelay(r);
1010 else {
1011 g.unipush(new UniRelay<T,T>(d, g));
1012 if (d.result == null)
1013 return null;
1014 }
1015 } catch (Throwable ex) {
1016 d.completeThrowable(ex);
1017 }
1018 }
1019 else
1020 d.internalComplete(r);
1021 }
1022 dep = null; src = null; fn = null;
1023 return d.postFire(a, mode);
1024 }
1025 }
1026
1027 private CompletableFuture<T> uniComposeExceptionallyStage(
1028 Executor e, Function<Throwable, ? extends CompletionStage<T>> f) {
1029 if (f == null) throw new NullPointerException();
1030 CompletableFuture<T> d = newIncompleteFuture();
1031 Object r, s; Throwable x;
1032 if ((r = result) == null)
1033 unipush(new UniComposeExceptionally<T>(e, d, this, f));
1034 else if (e == null) {
1035 if ((r instanceof AltResult) && (x = ((AltResult)r).ex) != null) {
1036 try {
1037 CompletableFuture<T> g = f.apply(x).toCompletableFuture();
1038 if ((s = g.result) != null)
1039 d.result = encodeRelay(s);
1040 else {
1041 g.unipush(new UniRelay<T,T>(d, g));
1042 }
1043 } catch (Throwable ex) {
1044 d.result = encodeThrowable(ex);
1045 }
1046 }
1047 else
1048 d.internalComplete(r);
1049 }
1050 else
1051 try {
1052 e.execute(new UniComposeExceptionally<T>(null, d, this, f));
1053 } catch (Throwable ex) {
1054 d.result = encodeThrowable(ex);
1055 }
1056 return d;
1057 }
1058
1059 @SuppressWarnings("serial")
1060 static final class UniRelay<U, T extends U> extends UniCompletion<T,U> {
1061 UniRelay(CompletableFuture<U> dep, CompletableFuture<T> src) {
1062 super(null, dep, src);
1063 }
1064 final CompletableFuture<U> tryFire(int mode) {
1065 CompletableFuture<U> d; CompletableFuture<T> a; Object r;
1066 if ((d = dep) == null
1067 || (a = src) == null || (r = a.result) == null)
1068 return null;
1069 if (d.result == null)
1070 d.completeRelay(r);
1071 src = null; dep = null;
1072 return d.postFire(a, mode);
1073 }
1074 }
1075
1076 private static <U, T extends U> CompletableFuture<U> uniCopyStage(
1077 CompletableFuture<T> src) {
1078 Object r;
1079 CompletableFuture<U> d = src.newIncompleteFuture();
1080 if ((r = src.result) != null)
1081 d.result = encodeRelay(r);
1082 else
1083 src.unipush(new UniRelay<U,T>(d, src));
1084 return d;
1085 }
1086
1087 private MinimalStage<T> uniAsMinimalStage() {
1088 Object r;
1089 if ((r = result) != null)
1090 return new MinimalStage<T>(encodeRelay(r));
1091 MinimalStage<T> d = new MinimalStage<T>();
1092 unipush(new UniRelay<T,T>(d, this));
1093 return d;
1094 }
1095
1096 @SuppressWarnings("serial")
1097 static final class UniCompose<T,V> extends UniCompletion<T,V> {
1098 Function<? super T, ? extends CompletionStage<V>> fn;
1099 UniCompose(Executor executor, CompletableFuture<V> dep,
1100 CompletableFuture<T> src,
1101 Function<? super T, ? extends CompletionStage<V>> fn) {
1102 super(executor, dep, src); this.fn = fn;
1103 }
1104 final CompletableFuture<V> tryFire(int mode) {
1105 CompletableFuture<V> d; CompletableFuture<T> a;
1106 Function<? super T, ? extends CompletionStage<V>> f;
1107 Object r; Throwable x;
1108 if ((d = dep) == null || (f = fn) == null
1109 || (a = src) == null || (r = a.result) == null)
1110 return null;
1111 tryComplete: if (d.result == null) {
1112 if (r instanceof AltResult) {
1113 if ((x = ((AltResult)r).ex) != null) {
1114 d.completeThrowable(x, r);
1115 break tryComplete;
1116 }
1117 r = null;
1118 }
1119 try {
1120 if (mode <= 0 && !claim())
1121 return null;
1122 @SuppressWarnings("unchecked") T t = (T) r;
1123 CompletableFuture<V> g = f.apply(t).toCompletableFuture();
1124 if ((r = g.result) != null)
1125 d.completeRelay(r);
1126 else {
1127 g.unipush(new UniRelay<V,V>(d, g));
1128 if (d.result == null)
1129 return null;
1130 }
1131 } catch (Throwable ex) {
1132 d.completeThrowable(ex);
1133 }
1134 }
1135 dep = null; src = null; fn = null;
1136 return d.postFire(a, mode);
1137 }
1138 }
1139
1140 private <V> CompletableFuture<V> uniComposeStage(
1141 Executor e, Function<? super T, ? extends CompletionStage<V>> f) {
1142 if (f == null) throw new NullPointerException();
1143 CompletableFuture<V> d = newIncompleteFuture();
1144 Object r, s; Throwable x;
1145 if ((r = result) == null)
1146 unipush(new UniCompose<T,V>(e, d, this, f));
1147 else if (e == null) {
1148 if (r instanceof AltResult) {
1149 if ((x = ((AltResult)r).ex) != null) {
1150 d.result = encodeThrowable(x, r);
1151 return d;
1152 }
1153 r = null;
1154 }
1155 try {
1156 @SuppressWarnings("unchecked") T t = (T) r;
1157 CompletableFuture<V> g = f.apply(t).toCompletableFuture();
1158 if ((s = g.result) != null)
1159 d.result = encodeRelay(s);
1160 else {
1161 g.unipush(new UniRelay<V,V>(d, g));
1162 }
1163 } catch (Throwable ex) {
1164 d.result = encodeThrowable(ex);
1165 }
1166 }
1167 else
1168 try {
1169 e.execute(new UniCompose<T,V>(null, d, this, f));
1170 } catch (Throwable ex) {
1171 d.result = encodeThrowable(ex);
1172 }
1173 return d;
1174 }
1175
1176 /* ------------- Two-input Completions -------------- */
1177
1178 /** A Completion for an action with two sources */
1179 @SuppressWarnings("serial")
1180 abstract static class BiCompletion<T,U,V> extends UniCompletion<T,V> {
1181 CompletableFuture<U> snd; // second source for action
1182 BiCompletion(Executor executor, CompletableFuture<V> dep,
1183 CompletableFuture<T> src, CompletableFuture<U> snd) {
1184 super(executor, dep, src); this.snd = snd;
1185 }
1186 }
1187
1188 /** A Completion delegating to a BiCompletion */
1189 @SuppressWarnings("serial")
1190 static final class CoCompletion extends Completion {
1191 BiCompletion<?,?,?> base;
1192 CoCompletion(BiCompletion<?,?,?> base) { this.base = base; }
1193 final CompletableFuture<?> tryFire(int mode) {
1194 BiCompletion<?,?,?> c; CompletableFuture<?> d;
1195 if ((c = base) == null || (d = c.tryFire(mode)) == null)
1196 return null;
1197 base = null; // detach
1198 return d;
1199 }
1200 final boolean isLive() {
1201 BiCompletion<?,?,?> c;
1202 return (c = base) != null
1203 // && c.isLive()
1204 && c.dep != null;
1205 }
1206 }
1207
1208 /**
1209 * Pushes completion to this and b unless both done.
1210 * Caller should first check that either result or b.result is null.
1211 */
1212 final void bipush(CompletableFuture<?> b, BiCompletion<?,?,?> c) {
1213 if (c != null) {
1214 while (result == null) {
1215 if (tryPushStack(c)) {
1216 if (b.result == null)
1217 b.unipush(new CoCompletion(c));
1218 else if (result != null)
1219 c.tryFire(SYNC);
1220 return;
1221 }
1222 }
1223 b.unipush(c);
1224 }
1225 }
1226
1227 /** Post-processing after successful BiCompletion tryFire. */
1228 final CompletableFuture<T> postFire(CompletableFuture<?> a,
1229 CompletableFuture<?> b, int mode) {
1230 if (b != null && b.stack != null) { // clean second source
1231 Object r;
1232 if ((r = b.result) == null)
1233 b.cleanStack();
1234 if (mode >= 0 && (r != null || b.result != null))
1235 b.postComplete();
1236 }
1237 return postFire(a, mode);
1238 }
1239
1240 @SuppressWarnings("serial")
1241 static final class BiApply<T,U,V> extends BiCompletion<T,U,V> {
1242 BiFunction<? super T,? super U,? extends V> fn;
1243 BiApply(Executor executor, CompletableFuture<V> dep,
1244 CompletableFuture<T> src, CompletableFuture<U> snd,
1245 BiFunction<? super T,? super U,? extends V> fn) {
1246 super(executor, dep, src, snd); this.fn = fn;
1247 }
1248 final CompletableFuture<V> tryFire(int mode) {
1249 CompletableFuture<V> d;
1250 CompletableFuture<T> a;
1251 CompletableFuture<U> b;
1252 Object r, s; BiFunction<? super T,? super U,? extends V> f;
1253 if ((d = dep) == null || (f = fn) == null
1254 || (a = src) == null || (r = a.result) == null
1255 || (b = snd) == null || (s = b.result) == null
1256 || !d.biApply(r, s, f, mode > 0 ? null : this))
1257 return null;
1258 dep = null; src = null; snd = null; fn = null;
1259 return d.postFire(a, b, mode);
1260 }
1261 }
1262
1263 final <R,S> boolean biApply(Object r, Object s,
1264 BiFunction<? super R,? super S,? extends T> f,
1265 BiApply<R,S,T> c) {
1266 Throwable x;
1267 tryComplete: if (result == null) {
1268 if (r instanceof AltResult) {
1269 if ((x = ((AltResult)r).ex) != null) {
1270 completeThrowable(x, r);
1271 break tryComplete;
1272 }
1273 r = null;
1274 }
1275 if (s instanceof AltResult) {
1276 if ((x = ((AltResult)s).ex) != null) {
1277 completeThrowable(x, s);
1278 break tryComplete;
1279 }
1280 s = null;
1281 }
1282 try {
1283 if (c != null && !c.claim())
1284 return false;
1285 @SuppressWarnings("unchecked") R rr = (R) r;
1286 @SuppressWarnings("unchecked") S ss = (S) s;
1287 completeValue(f.apply(rr, ss));
1288 } catch (Throwable ex) {
1289 completeThrowable(ex);
1290 }
1291 }
1292 return true;
1293 }
1294
1295 private <U,V> CompletableFuture<V> biApplyStage(
1296 Executor e, CompletionStage<U> o,
1297 BiFunction<? super T,? super U,? extends V> f) {
1298 CompletableFuture<U> b; Object r, s;
1299 if (f == null || (b = o.toCompletableFuture()) == null)
1300 throw new NullPointerException();
1301 CompletableFuture<V> d = newIncompleteFuture();
1302 if ((r = result) == null || (s = b.result) == null)
1303 bipush(b, new BiApply<T,U,V>(e, d, this, b, f));
1304 else if (e == null)
1305 d.biApply(r, s, f, null);
1306 else
1307 try {
1308 e.execute(new BiApply<T,U,V>(null, d, this, b, f));
1309 } catch (Throwable ex) {
1310 d.result = encodeThrowable(ex);
1311 }
1312 return d;
1313 }
1314
1315 @SuppressWarnings("serial")
1316 static final class BiAccept<T,U> extends BiCompletion<T,U,Void> {
1317 BiConsumer<? super T,? super U> fn;
1318 BiAccept(Executor executor, CompletableFuture<Void> dep,
1319 CompletableFuture<T> src, CompletableFuture<U> snd,
1320 BiConsumer<? super T,? super U> fn) {
1321 super(executor, dep, src, snd); this.fn = fn;
1322 }
1323 final CompletableFuture<Void> tryFire(int mode) {
1324 CompletableFuture<Void> d;
1325 CompletableFuture<T> a;
1326 CompletableFuture<U> b;
1327 Object r, s; BiConsumer<? super T,? super U> f;
1328 if ((d = dep) == null || (f = fn) == null
1329 || (a = src) == null || (r = a.result) == null
1330 || (b = snd) == null || (s = b.result) == null
1331 || !d.biAccept(r, s, f, mode > 0 ? null : this))
1332 return null;
1333 dep = null; src = null; snd = null; fn = null;
1334 return d.postFire(a, b, mode);
1335 }
1336 }
1337
1338 final <R,S> boolean biAccept(Object r, Object s,
1339 BiConsumer<? super R,? super S> f,
1340 BiAccept<R,S> c) {
1341 Throwable x;
1342 tryComplete: if (result == null) {
1343 if (r instanceof AltResult) {
1344 if ((x = ((AltResult)r).ex) != null) {
1345 completeThrowable(x, r);
1346 break tryComplete;
1347 }
1348 r = null;
1349 }
1350 if (s instanceof AltResult) {
1351 if ((x = ((AltResult)s).ex) != null) {
1352 completeThrowable(x, s);
1353 break tryComplete;
1354 }
1355 s = null;
1356 }
1357 try {
1358 if (c != null && !c.claim())
1359 return false;
1360 @SuppressWarnings("unchecked") R rr = (R) r;
1361 @SuppressWarnings("unchecked") S ss = (S) s;
1362 f.accept(rr, ss);
1363 completeNull();
1364 } catch (Throwable ex) {
1365 completeThrowable(ex);
1366 }
1367 }
1368 return true;
1369 }
1370
1371 private <U> CompletableFuture<Void> biAcceptStage(
1372 Executor e, CompletionStage<U> o,
1373 BiConsumer<? super T,? super U> f) {
1374 CompletableFuture<U> b; Object r, s;
1375 if (f == null || (b = o.toCompletableFuture()) == null)
1376 throw new NullPointerException();
1377 CompletableFuture<Void> d = newIncompleteFuture();
1378 if ((r = result) == null || (s = b.result) == null)
1379 bipush(b, new BiAccept<T,U>(e, d, this, b, f));
1380 else if (e == null)
1381 d.biAccept(r, s, f, null);
1382 else
1383 try {
1384 e.execute(new BiAccept<T,U>(null, d, this, b, f));
1385 } catch (Throwable ex) {
1386 d.result = encodeThrowable(ex);
1387 }
1388 return d;
1389 }
1390
1391 @SuppressWarnings("serial")
1392 static final class BiRun<T,U> extends BiCompletion<T,U,Void> {
1393 Runnable fn;
1394 BiRun(Executor executor, CompletableFuture<Void> dep,
1395 CompletableFuture<T> src, CompletableFuture<U> snd,
1396 Runnable fn) {
1397 super(executor, dep, src, snd); this.fn = fn;
1398 }
1399 final CompletableFuture<Void> tryFire(int mode) {
1400 CompletableFuture<Void> d;
1401 CompletableFuture<T> a;
1402 CompletableFuture<U> b;
1403 Object r, s; Runnable f;
1404 if ((d = dep) == null || (f = fn) == null
1405 || (a = src) == null || (r = a.result) == null
1406 || (b = snd) == null || (s = b.result) == null
1407 || !d.biRun(r, s, f, mode > 0 ? null : this))
1408 return null;
1409 dep = null; src = null; snd = null; fn = null;
1410 return d.postFire(a, b, mode);
1411 }
1412 }
1413
1414 final boolean biRun(Object r, Object s, Runnable f, BiRun<?,?> c) {
1415 Throwable x; Object z;
1416 if (result == null) {
1417 if ((r instanceof AltResult
1418 && (x = ((AltResult)(z = r)).ex) != null) ||
1419 (s instanceof AltResult
1420 && (x = ((AltResult)(z = s)).ex) != null))
1421 completeThrowable(x, z);
1422 else
1423 try {
1424 if (c != null && !c.claim())
1425 return false;
1426 f.run();
1427 completeNull();
1428 } catch (Throwable ex) {
1429 completeThrowable(ex);
1430 }
1431 }
1432 return true;
1433 }
1434
1435 private CompletableFuture<Void> biRunStage(Executor e, CompletionStage<?> o,
1436 Runnable f) {
1437 CompletableFuture<?> b; Object r, s;
1438 if (f == null || (b = o.toCompletableFuture()) == null)
1439 throw new NullPointerException();
1440 CompletableFuture<Void> d = newIncompleteFuture();
1441 if ((r = result) == null || (s = b.result) == null)
1442 bipush(b, new BiRun<>(e, d, this, b, f));
1443 else if (e == null)
1444 d.biRun(r, s, f, null);
1445 else
1446 try {
1447 e.execute(new BiRun<>(null, d, this, b, f));
1448 } catch (Throwable ex) {
1449 d.result = encodeThrowable(ex);
1450 }
1451 return d;
1452 }
1453
1454 @SuppressWarnings("serial")
1455 static final class BiRelay<T,U> extends BiCompletion<T,U,Void> { // for And
1456 BiRelay(CompletableFuture<Void> dep,
1457 CompletableFuture<T> src, CompletableFuture<U> snd) {
1458 super(null, dep, src, snd);
1459 }
1460 final CompletableFuture<Void> tryFire(int mode) {
1461 CompletableFuture<Void> d;
1462 CompletableFuture<T> a;
1463 CompletableFuture<U> b;
1464 Object r, s, z; Throwable x;
1465 if ((d = dep) == null
1466 || (a = src) == null || (r = a.result) == null
1467 || (b = snd) == null || (s = b.result) == null)
1468 return null;
1469 if (d.result == null) {
1470 if ((r instanceof AltResult
1471 && (x = ((AltResult)(z = r)).ex) != null) ||
1472 (s instanceof AltResult
1473 && (x = ((AltResult)(z = s)).ex) != null))
1474 d.completeThrowable(x, z);
1475 else
1476 d.completeNull();
1477 }
1478 src = null; snd = null; dep = null;
1479 return d.postFire(a, b, mode);
1480 }
1481 }
1482
1483 /** Recursively constructs a tree of completions. */
1484 static CompletableFuture<Void> andTree(CompletableFuture<?>[] cfs,
1485 int lo, int hi) {
1486 CompletableFuture<Void> d = new CompletableFuture<Void>();
1487 if (lo > hi) // empty
1488 d.result = NIL;
1489 else {
1490 CompletableFuture<?> a, b; Object r, s, z; Throwable x;
1491 int mid = (lo + hi) >>> 1;
1492 if ((a = (lo == mid ? cfs[lo] :
1493 andTree(cfs, lo, mid))) == null ||
1494 (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
1495 andTree(cfs, mid+1, hi))) == null)
1496 throw new NullPointerException();
1497 if ((r = a.result) == null || (s = b.result) == null)
1498 a.bipush(b, new BiRelay<>(d, a, b));
1499 else if ((r instanceof AltResult
1500 && (x = ((AltResult)(z = r)).ex) != null) ||
1501 (s instanceof AltResult
1502 && (x = ((AltResult)(z = s)).ex) != null))
1503 d.result = encodeThrowable(x, z);
1504 else
1505 d.result = NIL;
1506 }
1507 return d;
1508 }
1509
1510 /* ------------- Projected (Ored) BiCompletions -------------- */
1511
1512 /**
1513 * Pushes completion to this and b unless either done.
1514 * Caller should first check that result and b.result are both null.
1515 */
1516 final void orpush(CompletableFuture<?> b, BiCompletion<?,?,?> c) {
1517 if (c != null) {
1518 while (!tryPushStack(c)) {
1519 if (result != null) {
1520 NEXT.set(c, null);
1521 break;
1522 }
1523 }
1524 if (result != null)
1525 c.tryFire(SYNC);
1526 else
1527 b.unipush(new CoCompletion(c));
1528 }
1529 }
1530
1531 @SuppressWarnings("serial")
1532 static final class OrApply<T,U extends T,V> extends BiCompletion<T,U,V> {
1533 Function<? super T,? extends V> fn;
1534 OrApply(Executor executor, CompletableFuture<V> dep,
1535 CompletableFuture<T> src, CompletableFuture<U> snd,
1536 Function<? super T,? extends V> fn) {
1537 super(executor, dep, src, snd); this.fn = fn;
1538 }
1539 final CompletableFuture<V> tryFire(int mode) {
1540 CompletableFuture<V> d;
1541 CompletableFuture<T> a;
1542 CompletableFuture<U> b;
1543 Object r; Throwable x; Function<? super T,? extends V> f;
1544 if ((d = dep) == null || (f = fn) == null
1545 || (a = src) == null || (b = snd) == null
1546 || ((r = a.result) == null && (r = b.result) == null))
1547 return null;
1548 tryComplete: if (d.result == null) {
1549 try {
1550 if (mode <= 0 && !claim())
1551 return null;
1552 if (r instanceof AltResult) {
1553 if ((x = ((AltResult)r).ex) != null) {
1554 d.completeThrowable(x, r);
1555 break tryComplete;
1556 }
1557 r = null;
1558 }
1559 @SuppressWarnings("unchecked") T t = (T) r;
1560 d.completeValue(f.apply(t));
1561 } catch (Throwable ex) {
1562 d.completeThrowable(ex);
1563 }
1564 }
1565 dep = null; src = null; snd = null; fn = null;
1566 return d.postFire(a, b, mode);
1567 }
1568 }
1569
1570 private <U extends T,V> CompletableFuture<V> orApplyStage(
1571 Executor e, CompletionStage<U> o, Function<? super T, ? extends V> f) {
1572 CompletableFuture<U> b;
1573 if (f == null || (b = o.toCompletableFuture()) == null)
1574 throw new NullPointerException();
1575
1576 Object r; CompletableFuture<? extends T> z;
1577 if ((r = (z = this).result) != null ||
1578 (r = (z = b).result) != null)
1579 return z.uniApplyNow(r, e, f);
1580
1581 CompletableFuture<V> d = newIncompleteFuture();
1582 orpush(b, new OrApply<T,U,V>(e, d, this, b, f));
1583 return d;
1584 }
1585
1586 @SuppressWarnings("serial")
1587 static final class OrAccept<T,U extends T> extends BiCompletion<T,U,Void> {
1588 Consumer<? super T> fn;
1589 OrAccept(Executor executor, CompletableFuture<Void> dep,
1590 CompletableFuture<T> src, CompletableFuture<U> snd,
1591 Consumer<? super T> fn) {
1592 super(executor, dep, src, snd); this.fn = fn;
1593 }
1594 final CompletableFuture<Void> tryFire(int mode) {
1595 CompletableFuture<Void> d;
1596 CompletableFuture<T> a;
1597 CompletableFuture<U> b;
1598 Object r; Throwable x; Consumer<? super T> f;
1599 if ((d = dep) == null || (f = fn) == null
1600 || (a = src) == null || (b = snd) == null
1601 || ((r = a.result) == null && (r = b.result) == null))
1602 return null;
1603 tryComplete: if (d.result == null) {
1604 try {
1605 if (mode <= 0 && !claim())
1606 return null;
1607 if (r instanceof AltResult) {
1608 if ((x = ((AltResult)r).ex) != null) {
1609 d.completeThrowable(x, r);
1610 break tryComplete;
1611 }
1612 r = null;
1613 }
1614 @SuppressWarnings("unchecked") T t = (T) r;
1615 f.accept(t);
1616 d.completeNull();
1617 } catch (Throwable ex) {
1618 d.completeThrowable(ex);
1619 }
1620 }
1621 dep = null; src = null; snd = null; fn = null;
1622 return d.postFire(a, b, mode);
1623 }
1624 }
1625
1626 private <U extends T> CompletableFuture<Void> orAcceptStage(
1627 Executor e, CompletionStage<U> o, Consumer<? super T> f) {
1628 CompletableFuture<U> b;
1629 if (f == null || (b = o.toCompletableFuture()) == null)
1630 throw new NullPointerException();
1631
1632 Object r; CompletableFuture<? extends T> z;
1633 if ((r = (z = this).result) != null ||
1634 (r = (z = b).result) != null)
1635 return z.uniAcceptNow(r, e, f);
1636
1637 CompletableFuture<Void> d = newIncompleteFuture();
1638 orpush(b, new OrAccept<T,U>(e, d, this, b, f));
1639 return d;
1640 }
1641
1642 @SuppressWarnings("serial")
1643 static final class OrRun<T,U> extends BiCompletion<T,U,Void> {
1644 Runnable fn;
1645 OrRun(Executor executor, CompletableFuture<Void> dep,
1646 CompletableFuture<T> src, CompletableFuture<U> snd,
1647 Runnable fn) {
1648 super(executor, dep, src, snd); this.fn = fn;
1649 }
1650 final CompletableFuture<Void> tryFire(int mode) {
1651 CompletableFuture<Void> d;
1652 CompletableFuture<T> a;
1653 CompletableFuture<U> b;
1654 Object r; Throwable x; Runnable f;
1655 if ((d = dep) == null || (f = fn) == null
1656 || (a = src) == null || (b = snd) == null
1657 || ((r = a.result) == null && (r = b.result) == null))
1658 return null;
1659 if (d.result == null) {
1660 try {
1661 if (mode <= 0 && !claim())
1662 return null;
1663 else if (r instanceof AltResult
1664 && (x = ((AltResult)r).ex) != null)
1665 d.completeThrowable(x, r);
1666 else {
1667 f.run();
1668 d.completeNull();
1669 }
1670 } catch (Throwable ex) {
1671 d.completeThrowable(ex);
1672 }
1673 }
1674 dep = null; src = null; snd = null; fn = null;
1675 return d.postFire(a, b, mode);
1676 }
1677 }
1678
1679 private CompletableFuture<Void> orRunStage(Executor e, CompletionStage<?> o,
1680 Runnable f) {
1681 CompletableFuture<?> b;
1682 if (f == null || (b = o.toCompletableFuture()) == null)
1683 throw new NullPointerException();
1684
1685 Object r; CompletableFuture<?> z;
1686 if ((r = (z = this).result) != null ||
1687 (r = (z = b).result) != null)
1688 return z.uniRunNow(r, e, f);
1689
1690 CompletableFuture<Void> d = newIncompleteFuture();
1691 orpush(b, new OrRun<>(e, d, this, b, f));
1692 return d;
1693 }
1694
1695 /** Completion for an anyOf input future. */
1696 @SuppressWarnings("serial")
1697 static class AnyOf extends Completion {
1698 CompletableFuture<Object> dep; CompletableFuture<?> src;
1699 CompletableFuture<?>[] srcs;
1700 AnyOf(CompletableFuture<Object> dep, CompletableFuture<?> src,
1701 CompletableFuture<?>[] srcs) {
1702 this.dep = dep; this.src = src; this.srcs = srcs;
1703 }
1704 final CompletableFuture<Object> tryFire(int mode) {
1705 // assert mode != ASYNC;
1706 CompletableFuture<Object> d; CompletableFuture<?> a;
1707 CompletableFuture<?>[] as;
1708 Object r;
1709 if ((d = dep) == null
1710 || (a = src) == null || (r = a.result) == null
1711 || (as = srcs) == null)
1712 return null;
1713 dep = null; src = null; srcs = null;
1714 if (d.completeRelay(r)) {
1715 for (CompletableFuture<?> b : as)
1716 if (b != a)
1717 b.cleanStack();
1718 if (mode < 0)
1719 return d;
1720 else
1721 d.postComplete();
1722 }
1723 return null;
1724 }
1725 final boolean isLive() {
1726 CompletableFuture<Object> d;
1727 return (d = dep) != null && d.result == null;
1728 }
1729 }
1730
1731 /* ------------- Zero-input Async forms -------------- */
1732
1733 @SuppressWarnings("serial")
1734 static final class AsyncSupply<T> extends ForkJoinTask<Void>
1735 implements Runnable, AsynchronousCompletionTask {
1736 CompletableFuture<T> dep; Supplier<? extends T> fn;
1737 AsyncSupply(CompletableFuture<T> dep, Supplier<? extends T> fn) {
1738 this.dep = dep; this.fn = fn;
1739 }
1740
1741 public final Void getRawResult() { return null; }
1742 public final void setRawResult(Void v) {}
1743 public final boolean exec() { run(); return false; }
1744
1745 public void run() {
1746 CompletableFuture<T> d; Supplier<? extends T> f;
1747 if ((d = dep) != null && (f = fn) != null) {
1748 dep = null; fn = null;
1749 if (d.result == null) {
1750 try {
1751 d.completeValue(f.get());
1752 } catch (Throwable ex) {
1753 d.completeThrowable(ex);
1754 }
1755 }
1756 d.postComplete();
1757 }
1758 }
1759 }
1760
1761 static <U> CompletableFuture<U> asyncSupplyStage(Executor e,
1762 Supplier<U> f) {
1763 if (f == null) throw new NullPointerException();
1764 CompletableFuture<U> d = new CompletableFuture<U>();
1765 e.execute(new AsyncSupply<U>(d, f));
1766 return d;
1767 }
1768
1769 @SuppressWarnings("serial")
1770 static final class AsyncRun extends ForkJoinTask<Void>
1771 implements Runnable, AsynchronousCompletionTask {
1772 CompletableFuture<Void> dep; Runnable fn;
1773 AsyncRun(CompletableFuture<Void> dep, Runnable fn) {
1774 this.dep = dep; this.fn = fn;
1775 }
1776
1777 public final Void getRawResult() { return null; }
1778 public final void setRawResult(Void v) {}
1779 public final boolean exec() { run(); return false; }
1780
1781 public void run() {
1782 CompletableFuture<Void> d; Runnable f;
1783 if ((d = dep) != null && (f = fn) != null) {
1784 dep = null; fn = null;
1785 if (d.result == null) {
1786 try {
1787 f.run();
1788 d.completeNull();
1789 } catch (Throwable ex) {
1790 d.completeThrowable(ex);
1791 }
1792 }
1793 d.postComplete();
1794 }
1795 }
1796 }
1797
1798 static CompletableFuture<Void> asyncRunStage(Executor e, Runnable f) {
1799 if (f == null) throw new NullPointerException();
1800 CompletableFuture<Void> d = new CompletableFuture<Void>();
1801 e.execute(new AsyncRun(d, f));
1802 return d;
1803 }
1804
1805 /* ------------- Signallers -------------- */
1806
1807 /**
1808 * Completion for recording and releasing a waiting thread. This
1809 * class implements ManagedBlocker to avoid starvation when
1810 * blocking actions pile up in ForkJoinPools.
1811 */
1812 @SuppressWarnings("serial")
1813 static final class Signaller extends Completion
1814 implements ForkJoinPool.ManagedBlocker {
1815 long nanos; // remaining wait time if timed
1816 final long deadline; // non-zero if timed
1817 final boolean interruptible;
1818 boolean interrupted;
1819 volatile Thread thread;
1820
1821 Signaller(boolean interruptible, long nanos, long deadline) {
1822 this.thread = Thread.currentThread();
1823 this.interruptible = interruptible;
1824 this.nanos = nanos;
1825 this.deadline = deadline;
1826 }
1827 final CompletableFuture<?> tryFire(int ignore) {
1828 Thread w; // no need to atomically claim
1829 if ((w = thread) != null) {
1830 thread = null;
1831 LockSupport.unpark(w);
1832 }
1833 return null;
1834 }
1835 public boolean isReleasable() {
1836 if (Thread.interrupted())
1837 interrupted = true;
1838 return ((interrupted && interruptible) ||
1839 (deadline != 0L &&
1840 (nanos <= 0L ||
1841 (nanos = deadline - System.nanoTime()) <= 0L)) ||
1842 thread == null);
1843 }
1844 public boolean block() {
1845 while (!isReleasable()) {
1846 if (deadline == 0L)
1847 LockSupport.park(this);
1848 else
1849 LockSupport.parkNanos(this, nanos);
1850 }
1851 return true;
1852 }
1853 final boolean isLive() { return thread != null; }
1854 }
1855
1856 /**
1857 * Returns raw result after waiting, or null if interruptible and
1858 * interrupted.
1859 */
1860 private Object waitingGet(boolean interruptible) {
1861 Signaller q = null;
1862 boolean queued = false;
1863 Object r;
1864 while ((r = result) == null) {
1865 if (q == null) {
1866 q = new Signaller(interruptible, 0L, 0L);
1867 if (Thread.currentThread() instanceof ForkJoinWorkerThread)
1868 ForkJoinPool.helpAsyncBlocker(defaultExecutor(), q);
1869 }
1870 else if (!queued)
1871 queued = tryPushStack(q);
1872 else {
1873 try {
1874 ForkJoinPool.managedBlock(q);
1875 } catch (InterruptedException ie) { // currently cannot happen
1876 q.interrupted = true;
1877 }
1878 if (q.interrupted && interruptible)
1879 break;
1880 }
1881 }
1882 if (q != null && queued) {
1883 q.thread = null;
1884 if (!interruptible && q.interrupted)
1885 Thread.currentThread().interrupt();
1886 if (r == null)
1887 cleanStack();
1888 }
1889 if (r != null || (r = result) != null)
1890 postComplete();
1891 return r;
1892 }
1893
1894 /**
1895 * Returns raw result after waiting, or null if interrupted, or
1896 * throws TimeoutException on timeout.
1897 */
1898 private Object timedGet(long nanos) throws TimeoutException {
1899 if (Thread.interrupted())
1900 return null;
1901 if (nanos > 0L) {
1902 long d = System.nanoTime() + nanos;
1903 long deadline = (d == 0L) ? 1L : d; // avoid 0
1904 Signaller q = null;
1905 boolean queued = false;
1906 Object r;
1907 while ((r = result) == null) { // similar to untimed
1908 if (q == null) {
1909 q = new Signaller(true, nanos, deadline);
1910 if (Thread.currentThread() instanceof ForkJoinWorkerThread)
1911 ForkJoinPool.helpAsyncBlocker(defaultExecutor(), q);
1912 }
1913 else if (!queued)
1914 queued = tryPushStack(q);
1915 else if (q.nanos <= 0L)
1916 break;
1917 else {
1918 try {
1919 ForkJoinPool.managedBlock(q);
1920 } catch (InterruptedException ie) {
1921 q.interrupted = true;
1922 }
1923 if (q.interrupted)
1924 break;
1925 }
1926 }
1927 if (q != null && queued) {
1928 q.thread = null;
1929 if (r == null)
1930 cleanStack();
1931 }
1932 if (r != null || (r = result) != null)
1933 postComplete();
1934 if (r != null || (q != null && q.interrupted))
1935 return r;
1936 }
1937 throw new TimeoutException();
1938 }
1939
1940 /* ------------- public methods -------------- */
1941
1942 /**
1943 * Creates a new incomplete CompletableFuture.
1944 */
1945 public CompletableFuture() {
1946 }
1947
1948 /**
1949 * Creates a new complete CompletableFuture with given encoded result.
1950 */
1951 CompletableFuture(Object r) {
1952 RESULT.setRelease(this, r);
1953 }
1954
1955 /**
1956 * Returns a new CompletableFuture that is asynchronously completed
1957 * by a task running in the {@link ForkJoinPool#commonPool()} with
1958 * the value obtained by calling the given Supplier.
1959 *
1960 * @param supplier a function returning the value to be used
1961 * to complete the returned CompletableFuture
1962 * @param <U> the function's return type
1963 * @return the new CompletableFuture
1964 */
1965 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
1966 return asyncSupplyStage(ASYNC_POOL, supplier);
1967 }
1968
1969 /**
1970 * Returns a new CompletableFuture that is asynchronously completed
1971 * by a task running in the given executor with the value obtained
1972 * by calling the given Supplier.
1973 *
1974 * @param supplier a function returning the value to be used
1975 * to complete the returned CompletableFuture
1976 * @param executor the executor to use for asynchronous execution
1977 * @param <U> the function's return type
1978 * @return the new CompletableFuture
1979 */
1980 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
1981 Executor executor) {
1982 return asyncSupplyStage(screenExecutor(executor), supplier);
1983 }
1984
1985 /**
1986 * Returns a new CompletableFuture that is asynchronously completed
1987 * by a task running in the {@link ForkJoinPool#commonPool()} after
1988 * it runs the given action.
1989 *
1990 * @param runnable the action to run before completing the
1991 * returned CompletableFuture
1992 * @return the new CompletableFuture
1993 */
1994 public static CompletableFuture<Void> runAsync(Runnable runnable) {
1995 return asyncRunStage(ASYNC_POOL, runnable);
1996 }
1997
1998 /**
1999 * Returns a new CompletableFuture that is asynchronously completed
2000 * by a task running in the given executor after it runs the given
2001 * action.
2002 *
2003 * @param runnable the action to run before completing the
2004 * returned CompletableFuture
2005 * @param executor the executor to use for asynchronous execution
2006 * @return the new CompletableFuture
2007 */
2008 public static CompletableFuture<Void> runAsync(Runnable runnable,
2009 Executor executor) {
2010 return asyncRunStage(screenExecutor(executor), runnable);
2011 }
2012
2013 /**
2014 * Returns a new CompletableFuture that is already completed with
2015 * the given value.
2016 *
2017 * @param value the value
2018 * @param <U> the type of the value
2019 * @return the completed CompletableFuture
2020 */
2021 public static <U> CompletableFuture<U> completedFuture(U value) {
2022 return new CompletableFuture<U>((value == null) ? NIL : value);
2023 }
2024
2025 /**
2026 * Returns {@code true} if completed in any fashion: normally,
2027 * exceptionally, or via cancellation.
2028 *
2029 * @return {@code true} if completed
2030 */
2031 public boolean isDone() {
2032 return result != null;
2033 }
2034
2035 /**
2036 * Waits if necessary for this future to complete, and then
2037 * returns its result.
2038 *
2039 * @return the result value
2040 * @throws CancellationException if this future was cancelled
2041 * @throws ExecutionException if this future completed exceptionally
2042 * @throws InterruptedException if the current thread was interrupted
2043 * while waiting
2044 */
2045 @SuppressWarnings("unchecked")
2046 public T get() throws InterruptedException, ExecutionException {
2047 Object r;
2048 if ((r = result) == null)
2049 r = waitingGet(true);
2050 return (T) reportGet(r);
2051 }
2052
2053 /**
2054 * Waits if necessary for at most the given time for this future
2055 * to complete, and then returns its result, if available.
2056 *
2057 * @param timeout the maximum time to wait
2058 * @param unit the time unit of the timeout argument
2059 * @return the result value
2060 * @throws CancellationException if this future was cancelled
2061 * @throws ExecutionException if this future completed exceptionally
2062 * @throws InterruptedException if the current thread was interrupted
2063 * while waiting
2064 * @throws TimeoutException if the wait timed out
2065 */
2066 @SuppressWarnings("unchecked")
2067 public T get(long timeout, TimeUnit unit)
2068 throws InterruptedException, ExecutionException, TimeoutException {
2069 long nanos = unit.toNanos(timeout);
2070 Object r;
2071 if ((r = result) == null)
2072 r = timedGet(nanos);
2073 return (T) reportGet(r);
2074 }
2075
2076 /**
2077 * Returns the result value when complete, or throws an
2078 * (unchecked) exception if completed exceptionally. To better
2079 * conform with the use of common functional forms, if a
2080 * computation involved in the completion of this
2081 * CompletableFuture threw an exception, this method throws an
2082 * (unchecked) {@link CompletionException} with the underlying
2083 * exception as its cause.
2084 *
2085 * @return the result value
2086 * @throws CancellationException if the computation was cancelled
2087 * @throws CompletionException if this future completed
2088 * exceptionally or a completion computation threw an exception
2089 */
2090 @SuppressWarnings("unchecked")
2091 public T join() {
2092 Object r;
2093 if ((r = result) == null)
2094 r = waitingGet(false);
2095 return (T) reportJoin(r);
2096 }
2097
2098 /**
2099 * Returns the result value (or throws any encountered exception)
2100 * if completed, else returns the given valueIfAbsent.
2101 *
2102 * @param valueIfAbsent the value to return if not completed
2103 * @return the result value, if completed, else the given valueIfAbsent
2104 * @throws CancellationException if the computation was cancelled
2105 * @throws CompletionException if this future completed
2106 * exceptionally or a completion computation threw an exception
2107 */
2108 @SuppressWarnings("unchecked")
2109 public T getNow(T valueIfAbsent) {
2110 Object r;
2111 return ((r = result) == null) ? valueIfAbsent : (T) reportJoin(r);
2112 }
2113
2114 /**
2115 * If not already completed, sets the value returned by {@link
2116 * #get()} and related methods to the given value.
2117 *
2118 * @param value the result value
2119 * @return {@code true} if this invocation caused this CompletableFuture
2120 * to transition to a completed state, else {@code false}
2121 */
2122 public boolean complete(T value) {
2123 boolean triggered = completeValue(value);
2124 postComplete();
2125 return triggered;
2126 }
2127
2128 /**
2129 * If not already completed, causes invocations of {@link #get()}
2130 * and related methods to throw the given exception.
2131 *
2132 * @param ex the exception
2133 * @return {@code true} if this invocation caused this CompletableFuture
2134 * to transition to a completed state, else {@code false}
2135 */
2136 public boolean completeExceptionally(Throwable ex) {
2137 if (ex == null) throw new NullPointerException();
2138 boolean triggered = internalComplete(new AltResult(ex));
2139 postComplete();
2140 return triggered;
2141 }
2142
2143 public <U> CompletableFuture<U> thenApply(
2144 Function<? super T,? extends U> fn) {
2145 return uniApplyStage(null, fn);
2146 }
2147
2148 public <U> CompletableFuture<U> thenApplyAsync(
2149 Function<? super T,? extends U> fn) {
2150 return uniApplyStage(defaultExecutor(), fn);
2151 }
2152
2153 public <U> CompletableFuture<U> thenApplyAsync(
2154 Function<? super T,? extends U> fn, Executor executor) {
2155 return uniApplyStage(screenExecutor(executor), fn);
2156 }
2157
2158 public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
2159 return uniAcceptStage(null, action);
2160 }
2161
2162 public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
2163 return uniAcceptStage(defaultExecutor(), action);
2164 }
2165
2166 public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
2167 Executor executor) {
2168 return uniAcceptStage(screenExecutor(executor), action);
2169 }
2170
2171 public CompletableFuture<Void> thenRun(Runnable action) {
2172 return uniRunStage(null, action);
2173 }
2174
2175 public CompletableFuture<Void> thenRunAsync(Runnable action) {
2176 return uniRunStage(defaultExecutor(), action);
2177 }
2178
2179 public CompletableFuture<Void> thenRunAsync(Runnable action,
2180 Executor executor) {
2181 return uniRunStage(screenExecutor(executor), action);
2182 }
2183
2184 public <U,V> CompletableFuture<V> thenCombine(
2185 CompletionStage<? extends U> other,
2186 BiFunction<? super T,? super U,? extends V> fn) {
2187 return biApplyStage(null, other, fn);
2188 }
2189
2190 public <U,V> CompletableFuture<V> thenCombineAsync(
2191 CompletionStage<? extends U> other,
2192 BiFunction<? super T,? super U,? extends V> fn) {
2193 return biApplyStage(defaultExecutor(), other, fn);
2194 }
2195
2196 public <U,V> CompletableFuture<V> thenCombineAsync(
2197 CompletionStage<? extends U> other,
2198 BiFunction<? super T,? super U,? extends V> fn, Executor executor) {
2199 return biApplyStage(screenExecutor(executor), other, fn);
2200 }
2201
2202 public <U> CompletableFuture<Void> thenAcceptBoth(
2203 CompletionStage<? extends U> other,
2204 BiConsumer<? super T, ? super U> action) {
2205 return biAcceptStage(null, other, action);
2206 }
2207
2208 public <U> CompletableFuture<Void> thenAcceptBothAsync(
2209 CompletionStage<? extends U> other,
2210 BiConsumer<? super T, ? super U> action) {
2211 return biAcceptStage(defaultExecutor(), other, action);
2212 }
2213
2214 public <U> CompletableFuture<Void> thenAcceptBothAsync(
2215 CompletionStage<? extends U> other,
2216 BiConsumer<? super T, ? super U> action, Executor executor) {
2217 return biAcceptStage(screenExecutor(executor), other, action);
2218 }
2219
2220 public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,
2221 Runnable action) {
2222 return biRunStage(null, other, action);
2223 }
2224
2225 public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
2226 Runnable action) {
2227 return biRunStage(defaultExecutor(), other, action);
2228 }
2229
2230 public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
2231 Runnable action,
2232 Executor executor) {
2233 return biRunStage(screenExecutor(executor), other, action);
2234 }
2235
2236 public <U> CompletableFuture<U> applyToEither(
2237 CompletionStage<? extends T> other, Function<? super T, U> fn) {
2238 return orApplyStage(null, other, fn);
2239 }
2240
2241 public <U> CompletableFuture<U> applyToEitherAsync(
2242 CompletionStage<? extends T> other, Function<? super T, U> fn) {
2243 return orApplyStage(defaultExecutor(), other, fn);
2244 }
2245
2246 public <U> CompletableFuture<U> applyToEitherAsync(
2247 CompletionStage<? extends T> other, Function<? super T, U> fn,
2248 Executor executor) {
2249 return orApplyStage(screenExecutor(executor), other, fn);
2250 }
2251
2252 public CompletableFuture<Void> acceptEither(
2253 CompletionStage<? extends T> other, Consumer<? super T> action) {
2254 return orAcceptStage(null, other, action);
2255 }
2256
2257 public CompletableFuture<Void> acceptEitherAsync(
2258 CompletionStage<? extends T> other, Consumer<? super T> action) {
2259 return orAcceptStage(defaultExecutor(), other, action);
2260 }
2261
2262 public CompletableFuture<Void> acceptEitherAsync(
2263 CompletionStage<? extends T> other, Consumer<? super T> action,
2264 Executor executor) {
2265 return orAcceptStage(screenExecutor(executor), other, action);
2266 }
2267
2268 public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,
2269 Runnable action) {
2270 return orRunStage(null, other, action);
2271 }
2272
2273 public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
2274 Runnable action) {
2275 return orRunStage(defaultExecutor(), other, action);
2276 }
2277
2278 public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
2279 Runnable action,
2280 Executor executor) {
2281 return orRunStage(screenExecutor(executor), other, action);
2282 }
2283
2284 public <U> CompletableFuture<U> thenCompose(
2285 Function<? super T, ? extends CompletionStage<U>> fn) {
2286 return uniComposeStage(null, fn);
2287 }
2288
2289 public <U> CompletableFuture<U> thenComposeAsync(
2290 Function<? super T, ? extends CompletionStage<U>> fn) {
2291 return uniComposeStage(defaultExecutor(), fn);
2292 }
2293
2294 public <U> CompletableFuture<U> thenComposeAsync(
2295 Function<? super T, ? extends CompletionStage<U>> fn,
2296 Executor executor) {
2297 return uniComposeStage(screenExecutor(executor), fn);
2298 }
2299
2300 public CompletableFuture<T> whenComplete(
2301 BiConsumer<? super T, ? super Throwable> action) {
2302 return uniWhenCompleteStage(null, action);
2303 }
2304
2305 public CompletableFuture<T> whenCompleteAsync(
2306 BiConsumer<? super T, ? super Throwable> action) {
2307 return uniWhenCompleteStage(defaultExecutor(), action);
2308 }
2309
2310 public CompletableFuture<T> whenCompleteAsync(
2311 BiConsumer<? super T, ? super Throwable> action, Executor executor) {
2312 return uniWhenCompleteStage(screenExecutor(executor), action);
2313 }
2314
2315 public <U> CompletableFuture<U> handle(
2316 BiFunction<? super T, Throwable, ? extends U> fn) {
2317 return uniHandleStage(null, fn);
2318 }
2319
2320 public <U> CompletableFuture<U> handleAsync(
2321 BiFunction<? super T, Throwable, ? extends U> fn) {
2322 return uniHandleStage(defaultExecutor(), fn);
2323 }
2324
2325 public <U> CompletableFuture<U> handleAsync(
2326 BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) {
2327 return uniHandleStage(screenExecutor(executor), fn);
2328 }
2329
2330 /**
2331 * Returns this CompletableFuture.
2332 *
2333 * @return this CompletableFuture
2334 */
2335 public CompletableFuture<T> toCompletableFuture() {
2336 return this;
2337 }
2338
2339 public CompletableFuture<T> exceptionally(
2340 Function<Throwable, ? extends T> fn) {
2341 return uniExceptionallyStage(null, fn);
2342 }
2343
2344 public CompletableFuture<T> exceptionallyAsync(
2345 Function<Throwable, ? extends T> fn) {
2346 return uniExceptionallyStage(defaultExecutor(), fn);
2347 }
2348
2349 public CompletableFuture<T> exceptionallyAsync(
2350 Function<Throwable, ? extends T> fn, Executor executor) {
2351 return uniExceptionallyStage(screenExecutor(executor), fn);
2352 }
2353
2354 public CompletableFuture<T> exceptionallyCompose(
2355 Function<Throwable, ? extends CompletionStage<T>> fn) {
2356 return uniComposeExceptionallyStage(null, fn);
2357 }
2358
2359 public CompletableFuture<T> exceptionallyComposeAsync(
2360 Function<Throwable, ? extends CompletionStage<T>> fn) {
2361 return uniComposeExceptionallyStage(defaultExecutor(), fn);
2362 }
2363
2364 public CompletableFuture<T> exceptionallyComposeAsync(
2365 Function<Throwable, ? extends CompletionStage<T>> fn,
2366 Executor executor) {
2367 return uniComposeExceptionallyStage(screenExecutor(executor), fn);
2368 }
2369
2370 /* ------------- Arbitrary-arity constructions -------------- */
2371
2372 /**
2373 * Returns a new CompletableFuture that is completed when all of
2374 * the given CompletableFutures complete. If any of the given
2375 * CompletableFutures complete exceptionally, then the returned
2376 * CompletableFuture also does so, with a CompletionException
2377 * holding this exception as its cause. Otherwise, the results,
2378 * if any, of the given CompletableFutures are not reflected in
2379 * the returned CompletableFuture, but may be obtained by
2380 * inspecting them individually. If no CompletableFutures are
2381 * provided, returns a CompletableFuture completed with the value
2382 * {@code null}.
2383 *
2384 * <p>Among the applications of this method is to await completion
2385 * of a set of independent CompletableFutures before continuing a
2386 * program, as in: {@code CompletableFuture.allOf(c1, c2,
2387 * c3).join();}.
2388 *
2389 * @param cfs the CompletableFutures
2390 * @return a new CompletableFuture that is completed when all of the
2391 * given CompletableFutures complete
2392 * @throws NullPointerException if the array or any of its elements are
2393 * {@code null}
2394 */
2395 public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
2396 return andTree(cfs, 0, cfs.length - 1);
2397 }
2398
2399 /**
2400 * Returns a new CompletableFuture that is completed when any of
2401 * the given CompletableFutures complete, with the same result.
2402 * Otherwise, if it completed exceptionally, the returned
2403 * CompletableFuture also does so, with a CompletionException
2404 * holding this exception as its cause. If no CompletableFutures
2405 * are provided, returns an incomplete CompletableFuture.
2406 *
2407 * @param cfs the CompletableFutures
2408 * @return a new CompletableFuture that is completed with the
2409 * result or exception of any of the given CompletableFutures when
2410 * one completes
2411 * @throws NullPointerException if the array or any of its elements are
2412 * {@code null}
2413 */
2414 public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
2415 int n; Object r;
2416 if ((n = cfs.length) <= 1)
2417 return (n == 0)
2418 ? new CompletableFuture<Object>()
2419 : uniCopyStage(cfs[0]);
2420 for (CompletableFuture<?> cf : cfs)
2421 if ((r = cf.result) != null)
2422 return new CompletableFuture<Object>(encodeRelay(r));
2423 cfs = cfs.clone();
2424 CompletableFuture<Object> d = new CompletableFuture<>();
2425 for (CompletableFuture<?> cf : cfs)
2426 cf.unipush(new AnyOf(d, cf, cfs));
2427 // If d was completed while we were adding completions, we should
2428 // clean the stack of any sources that may have had completions
2429 // pushed on their stack after d was completed.
2430 if (d.result != null)
2431 for (int i = 0, len = cfs.length; i < len; i++)
2432 if (cfs[i].result != null)
2433 for (i++; i < len; i++)
2434 if (cfs[i].result == null)
2435 cfs[i].cleanStack();
2436 return d;
2437 }
2438
2439 /* ------------- Control and status methods -------------- */
2440
2441 /**
2442 * If not already completed, completes this CompletableFuture with
2443 * a {@link CancellationException}. Dependent CompletableFutures
2444 * that have not already completed will also complete
2445 * exceptionally, with a {@link CompletionException} caused by
2446 * this {@code CancellationException}.
2447 *
2448 * @param mayInterruptIfRunning this value has no effect in this
2449 * implementation because interrupts are not used to control
2450 * processing.
2451 *
2452 * @return {@code true} if this task is now cancelled
2453 */
2454 public boolean cancel(boolean mayInterruptIfRunning) {
2455 boolean cancelled = (result == null) &&
2456 internalComplete(new AltResult(new CancellationException()));
2457 postComplete();
2458 return cancelled || isCancelled();
2459 }
2460
2461 /**
2462 * Returns {@code true} if this CompletableFuture was cancelled
2463 * before it completed normally.
2464 *
2465 * @return {@code true} if this CompletableFuture was cancelled
2466 * before it completed normally
2467 */
2468 public boolean isCancelled() {
2469 Object r;
2470 return ((r = result) instanceof AltResult) &&
2471 (((AltResult)r).ex instanceof CancellationException);
2472 }
2473
2474 /**
2475 * Returns {@code true} if this CompletableFuture completed
2476 * exceptionally, in any way. Possible causes include
2477 * cancellation, explicit invocation of {@code
2478 * completeExceptionally}, and abrupt termination of a
2479 * CompletionStage action.
2480 *
2481 * @return {@code true} if this CompletableFuture completed
2482 * exceptionally
2483 */
2484 public boolean isCompletedExceptionally() {
2485 Object r;
2486 return ((r = result) instanceof AltResult) && r != NIL;
2487 }
2488
2489 /**
2490 * Forcibly sets or resets the value subsequently returned by
2491 * method {@link #get()} and related methods, whether or not
2492 * already completed. This method is designed for use only in
2493 * error recovery actions, and even in such situations may result
2494 * in ongoing dependent completions using established versus
2495 * overwritten outcomes.
2496 *
2497 * @param value the completion value
2498 */
2499 public void obtrudeValue(T value) {
2500 result = (value == null) ? NIL : value;
2501 postComplete();
2502 }
2503
2504 /**
2505 * Forcibly causes subsequent invocations of method {@link #get()}
2506 * and related methods to throw the given exception, whether or
2507 * not already completed. This method is designed for use only in
2508 * error recovery actions, and even in such situations may result
2509 * in ongoing dependent completions using established versus
2510 * overwritten outcomes.
2511 *
2512 * @param ex the exception
2513 * @throws NullPointerException if the exception is null
2514 */
2515 public void obtrudeException(Throwable ex) {
2516 if (ex == null) throw new NullPointerException();
2517 result = new AltResult(ex);
2518 postComplete();
2519 }
2520
2521 /**
2522 * Returns the estimated number of CompletableFutures whose
2523 * completions are awaiting completion of this CompletableFuture.
2524 * This method is designed for use in monitoring system state, not
2525 * for synchronization control.
2526 *
2527 * @return the number of dependent CompletableFutures
2528 */
2529 public int getNumberOfDependents() {
2530 int count = 0;
2531 for (Completion p = stack; p != null; p = p.next)
2532 ++count;
2533 return count;
2534 }
2535
2536 /**
2537 * Returns a string identifying this CompletableFuture, as well as
2538 * its completion state. The state, in brackets, contains the
2539 * String {@code "Completed Normally"} or the String {@code
2540 * "Completed Exceptionally"}, or the String {@code "Not
2541 * completed"} followed by the number of CompletableFutures
2542 * dependent upon its completion, if any.
2543 *
2544 * @return a string identifying this CompletableFuture, as well as its state
2545 */
2546 public String toString() {
2547 Object r = result;
2548 int count = 0; // avoid call to getNumberOfDependents in case disabled
2549 for (Completion p = stack; p != null; p = p.next)
2550 ++count;
2551 return super.toString() +
2552 ((r == null)
2553 ? ((count == 0)
2554 ? "[Not completed]"
2555 : "[Not completed, " + count + " dependents]")
2556 : (((r instanceof AltResult) && ((AltResult)r).ex != null)
2557 ? "[Completed exceptionally: " + ((AltResult)r).ex + "]"
2558 : "[Completed normally]"));
2559 }
2560
2561 // jdk9 additions
2562
2563 /**
2564 * Returns a new incomplete CompletableFuture of the type to be
2565 * returned by a CompletionStage method. Subclasses should
2566 * normally override this method to return an instance of the same
2567 * class as this CompletableFuture. The default implementation
2568 * returns an instance of class CompletableFuture.
2569 *
2570 * @param <U> the type of the value
2571 * @return a new CompletableFuture
2572 * @since 9
2573 */
2574 public <U> CompletableFuture<U> newIncompleteFuture() {
2575 return new CompletableFuture<U>();
2576 }
2577
2578 /**
2579 * Returns the default Executor used for async methods that do not
2580 * specify an Executor. This class uses the {@link
2581 * ForkJoinPool#commonPool()} if it supports more than one
2582 * parallel thread, or else an Executor using one thread per async
2583 * task. This method may be overridden in subclasses to return
2584 * an Executor that provides at least one independent thread.
2585 *
2586 * @return the executor
2587 * @since 9
2588 */
2589 public Executor defaultExecutor() {
2590 return ASYNC_POOL;
2591 }
2592
2593 /**
2594 * Returns a new CompletableFuture that is completed normally with
2595 * the same value as this CompletableFuture when it completes
2596 * normally. If this CompletableFuture completes exceptionally,
2597 * then the returned CompletableFuture completes exceptionally
2598 * with a CompletionException with this exception as cause. The
2599 * behavior is equivalent to {@code thenApply(x -> x)}. This
2600 * method may be useful as a form of "defensive copying", to
2601 * prevent clients from completing, while still being able to
2602 * arrange dependent actions.
2603 *
2604 * @return the new CompletableFuture
2605 * @since 9
2606 */
2607 public CompletableFuture<T> copy() {
2608 return uniCopyStage(this);
2609 }
2610
2611 /**
2612 * Returns a new CompletionStage that is completed normally with
2613 * the same value as this CompletableFuture when it completes
2614 * normally, and cannot be independently completed or otherwise
2615 * used in ways not defined by the methods of interface {@link
2616 * CompletionStage}. If this CompletableFuture completes
2617 * exceptionally, then the returned CompletionStage completes
2618 * exceptionally with a CompletionException with this exception as
2619 * cause.
2620 *
2621 * <p>Unless overridden by a subclass, a new non-minimal
2622 * CompletableFuture with all methods available can be obtained from
2623 * a minimal CompletionStage via {@link #toCompletableFuture()}.
2624 * For example, completion of a minimal stage can be awaited by
2625 *
2626 * <pre> {@code minimalStage.toCompletableFuture().join(); }</pre>
2627 *
2628 * @return the new CompletionStage
2629 * @since 9
2630 */
2631 public CompletionStage<T> minimalCompletionStage() {
2632 return uniAsMinimalStage();
2633 }
2634
2635 /**
2636 * Completes this CompletableFuture with the result of
2637 * the given Supplier function invoked from an asynchronous
2638 * task using the given executor.
2639 *
2640 * @param supplier a function returning the value to be used
2641 * to complete this CompletableFuture
2642 * @param executor the executor to use for asynchronous execution
2643 * @return this CompletableFuture
2644 * @since 9
2645 */
2646 public CompletableFuture<T> completeAsync(Supplier<? extends T> supplier,
2647 Executor executor) {
2648 if (supplier == null || executor == null)
2649 throw new NullPointerException();
2650 executor.execute(new AsyncSupply<T>(this, supplier));
2651 return this;
2652 }
2653
2654 /**
2655 * Completes this CompletableFuture with the result of the given
2656 * Supplier function invoked from an asynchronous task using the
2657 * default executor.
2658 *
2659 * @param supplier a function returning the value to be used
2660 * to complete this CompletableFuture
2661 * @return this CompletableFuture
2662 * @since 9
2663 */
2664 public CompletableFuture<T> completeAsync(Supplier<? extends T> supplier) {
2665 return completeAsync(supplier, defaultExecutor());
2666 }
2667
2668 /**
2669 * Exceptionally completes this CompletableFuture with
2670 * a {@link TimeoutException} if not otherwise completed
2671 * before the given timeout.
2672 *
2673 * @param timeout how long to wait before completing exceptionally
2674 * with a TimeoutException, in units of {@code unit}
2675 * @param unit a {@code TimeUnit} determining how to interpret the
2676 * {@code timeout} parameter
2677 * @return this CompletableFuture
2678 * @since 9
2679 */
2680 public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit) {
2681 if (unit == null)
2682 throw new NullPointerException();
2683 if (result == null)
2684 whenComplete(new Canceller(Delayer.delay(new Timeout(this),
2685 timeout, unit)));
2686 return this;
2687 }
2688
2689 /**
2690 * Completes this CompletableFuture with the given value if not
2691 * otherwise completed before the given timeout.
2692 *
2693 * @param value the value to use upon timeout
2694 * @param timeout how long to wait before completing normally
2695 * with the given value, in units of {@code unit}
2696 * @param unit a {@code TimeUnit} determining how to interpret the
2697 * {@code timeout} parameter
2698 * @return this CompletableFuture
2699 * @since 9
2700 */
2701 public CompletableFuture<T> completeOnTimeout(T value, long timeout,
2702 TimeUnit unit) {
2703 if (unit == null)
2704 throw new NullPointerException();
2705 if (result == null)
2706 whenComplete(new Canceller(Delayer.delay(
2707 new DelayedCompleter<T>(this, value),
2708 timeout, unit)));
2709 return this;
2710 }
2711
2712 /**
2713 * Returns a new Executor that submits a task to the given base
2714 * executor after the given delay (or no delay if non-positive).
2715 * Each delay commences upon invocation of the returned executor's
2716 * {@code execute} method.
2717 *
2718 * @param delay how long to delay, in units of {@code unit}
2719 * @param unit a {@code TimeUnit} determining how to interpret the
2720 * {@code delay} parameter
2721 * @param executor the base executor
2722 * @return the new delayed executor
2723 * @since 9
2724 */
2725 public static Executor delayedExecutor(long delay, TimeUnit unit,
2726 Executor executor) {
2727 if (unit == null || executor == null)
2728 throw new NullPointerException();
2729 return new DelayedExecutor(delay, unit, executor);
2730 }
2731
2732 /**
2733 * Returns a new Executor that submits a task to the default
2734 * executor after the given delay (or no delay if non-positive).
2735 * Each delay commences upon invocation of the returned executor's
2736 * {@code execute} method.
2737 *
2738 * @param delay how long to delay, in units of {@code unit}
2739 * @param unit a {@code TimeUnit} determining how to interpret the
2740 * {@code delay} parameter
2741 * @return the new delayed executor
2742 * @since 9
2743 */
2744 public static Executor delayedExecutor(long delay, TimeUnit unit) {
2745 if (unit == null)
2746 throw new NullPointerException();
2747 return new DelayedExecutor(delay, unit, ASYNC_POOL);
2748 }
2749
2750 /**
2751 * Returns a new CompletionStage that is already completed with
2752 * the given value and supports only those methods in
2753 * interface {@link CompletionStage}.
2754 *
2755 * @param value the value
2756 * @param <U> the type of the value
2757 * @return the completed CompletionStage
2758 * @since 9
2759 */
2760 public static <U> CompletionStage<U> completedStage(U value) {
2761 return new MinimalStage<U>((value == null) ? NIL : value);
2762 }
2763
2764 /**
2765 * Returns a new CompletableFuture that is already completed
2766 * exceptionally with the given exception.
2767 *
2768 * @param ex the exception
2769 * @param <U> the type of the value
2770 * @return the exceptionally completed CompletableFuture
2771 * @since 9
2772 */
2773 public static <U> CompletableFuture<U> failedFuture(Throwable ex) {
2774 if (ex == null) throw new NullPointerException();
2775 return new CompletableFuture<U>(new AltResult(ex));
2776 }
2777
2778 /**
2779 * Returns a new CompletionStage that is already completed
2780 * exceptionally with the given exception and supports only those
2781 * methods in interface {@link CompletionStage}.
2782 *
2783 * @param ex the exception
2784 * @param <U> the type of the value
2785 * @return the exceptionally completed CompletionStage
2786 * @since 9
2787 */
2788 public static <U> CompletionStage<U> failedStage(Throwable ex) {
2789 if (ex == null) throw new NullPointerException();
2790 return new MinimalStage<U>(new AltResult(ex));
2791 }
2792
2793 /**
2794 * Singleton delay scheduler, used only for starting and
2795 * cancelling tasks.
2796 */
2797 static final class Delayer {
2798 static ScheduledFuture<?> delay(Runnable command, long delay,
2799 TimeUnit unit) {
2800 return delayer.schedule(command, delay, unit);
2801 }
2802
2803 static final class DaemonThreadFactory implements ThreadFactory {
2804 public Thread newThread(Runnable r) {
2805 Thread t = new Thread(r);
2806 t.setDaemon(true);
2807 t.setName("CompletableFutureDelayScheduler");
2808 return t;
2809 }
2810 }
2811
2812 static final ScheduledThreadPoolExecutor delayer;
2813 static {
2814 (delayer = new ScheduledThreadPoolExecutor(
2815 1, new DaemonThreadFactory())).
2816 setRemoveOnCancelPolicy(true);
2817 }
2818 }
2819
2820 // Little class-ified lambdas to better support monitoring
2821
2822 static final class DelayedExecutor implements Executor {
2823 final long delay;
2824 final TimeUnit unit;
2825 final Executor executor;
2826 DelayedExecutor(long delay, TimeUnit unit, Executor executor) {
2827 this.delay = delay; this.unit = unit; this.executor = executor;
2828 }
2829 public void execute(Runnable r) {
2830 Delayer.delay(new TaskSubmitter(executor, r), delay, unit);
2831 }
2832 }
2833
2834 /** Action to submit user task */
2835 static final class TaskSubmitter implements Runnable {
2836 final Executor executor;
2837 final Runnable action;
2838 TaskSubmitter(Executor executor, Runnable action) {
2839 this.executor = executor;
2840 this.action = action;
2841 }
2842 public void run() { executor.execute(action); }
2843 }
2844
2845 /** Action to completeExceptionally on timeout */
2846 static final class Timeout implements Runnable {
2847 final CompletableFuture<?> f;
2848 Timeout(CompletableFuture<?> f) { this.f = f; }
2849 public void run() {
2850 if (f != null && !f.isDone())
2851 f.completeExceptionally(new TimeoutException());
2852 }
2853 }
2854
2855 /** Action to complete on timeout */
2856 static final class DelayedCompleter<U> implements Runnable {
2857 final CompletableFuture<U> f;
2858 final U u;
2859 DelayedCompleter(CompletableFuture<U> f, U u) { this.f = f; this.u = u; }
2860 public void run() {
2861 if (f != null)
2862 f.complete(u);
2863 }
2864 }
2865
2866 /** Action to cancel unneeded timeouts */
2867 static final class Canceller implements BiConsumer<Object, Throwable> {
2868 final Future<?> f;
2869 Canceller(Future<?> f) { this.f = f; }
2870 public void accept(Object ignore, Throwable ex) {
2871 if (ex == null && f != null && !f.isDone())
2872 f.cancel(false);
2873 }
2874 }
2875
2876 /**
2877 * A subclass that just throws UOE for most non-CompletionStage methods.
2878 */
2879 static final class MinimalStage<T> extends CompletableFuture<T> {
2880 MinimalStage() { }
2881 MinimalStage(Object r) { super(r); }
2882 @Override public <U> CompletableFuture<U> newIncompleteFuture() {
2883 return new MinimalStage<U>(); }
2884 @Override public T get() {
2885 throw new UnsupportedOperationException(); }
2886 @Override public T get(long timeout, TimeUnit unit) {
2887 throw new UnsupportedOperationException(); }
2888 @Override public T getNow(T valueIfAbsent) {
2889 throw new UnsupportedOperationException(); }
2890 @Override public T join() {
2891 throw new UnsupportedOperationException(); }
2892 @Override public boolean complete(T value) {
2893 throw new UnsupportedOperationException(); }
2894 @Override public boolean completeExceptionally(Throwable ex) {
2895 throw new UnsupportedOperationException(); }
2896 @Override public boolean cancel(boolean mayInterruptIfRunning) {
2897 throw new UnsupportedOperationException(); }
2898 @Override public void obtrudeValue(T value) {
2899 throw new UnsupportedOperationException(); }
2900 @Override public void obtrudeException(Throwable ex) {
2901 throw new UnsupportedOperationException(); }
2902 @Override public boolean isDone() {
2903 throw new UnsupportedOperationException(); }
2904 @Override public boolean isCancelled() {
2905 throw new UnsupportedOperationException(); }
2906 @Override public boolean isCompletedExceptionally() {
2907 throw new UnsupportedOperationException(); }
2908 @Override public int getNumberOfDependents() {
2909 throw new UnsupportedOperationException(); }
2910 @Override public CompletableFuture<T> completeAsync
2911 (Supplier<? extends T> supplier, Executor executor) {
2912 throw new UnsupportedOperationException(); }
2913 @Override public CompletableFuture<T> completeAsync
2914 (Supplier<? extends T> supplier) {
2915 throw new UnsupportedOperationException(); }
2916 @Override public CompletableFuture<T> orTimeout
2917 (long timeout, TimeUnit unit) {
2918 throw new UnsupportedOperationException(); }
2919 @Override public CompletableFuture<T> completeOnTimeout
2920 (T value, long timeout, TimeUnit unit) {
2921 throw new UnsupportedOperationException(); }
2922 @Override public CompletableFuture<T> toCompletableFuture() {
2923 Object r;
2924 if ((r = result) != null)
2925 return new CompletableFuture<T>(encodeRelay(r));
2926 else {
2927 CompletableFuture<T> d = new CompletableFuture<>();
2928 unipush(new UniRelay<T,T>(d, this));
2929 return d;
2930 }
2931 }
2932 }
2933
2934 // VarHandle mechanics
2935 private static final VarHandle RESULT;
2936 private static final VarHandle STACK;
2937 private static final VarHandle NEXT;
2938 static {
2939 try {
2940 MethodHandles.Lookup l = MethodHandles.lookup();
2941 RESULT = l.findVarHandle(CompletableFuture.class, "result", Object.class);
2942 STACK = l.findVarHandle(CompletableFuture.class, "stack", Completion.class);
2943 NEXT = l.findVarHandle(Completion.class, "next", Completion.class);
2944 } catch (ReflectiveOperationException e) {
2945 throw new ExceptionInInitializerError(e);
2946 }
2947
2948 // Reduce the risk of rare disastrous classloading in first call to
2949 // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
2950 Class<?> ensureLoaded = LockSupport.class;
2951 }
2952 }