ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.197
Committed: Mon Jun 20 21:05:28 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.196: +3 -1 lines
Log Message:
add a comment documenting brittleness in CoCompletion.isLive()

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