ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.198
Committed: Mon Jun 20 23:30:05 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.197: +30 -36 lines
Log Message:
bipush/orpush should call tryFire if complete

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