ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.116
Committed: Mon May 26 06:36:25 2014 UTC (10 years ago) by jsr166
Branch: MAIN
Changes since 1.115: +1 -1 lines
Log Message:
javadoc style

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 import java.util.function.Supplier;
9 import java.util.function.Consumer;
10 import java.util.function.BiConsumer;
11 import java.util.function.Function;
12 import java.util.function.BiFunction;
13 import java.util.concurrent.Future;
14 import java.util.concurrent.TimeUnit;
15 import java.util.concurrent.ForkJoinPool;
16 import java.util.concurrent.ForkJoinTask;
17 import java.util.concurrent.Executor;
18 import java.util.concurrent.ThreadLocalRandom;
19 import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.TimeoutException;
21 import java.util.concurrent.CancellationException;
22 import java.util.concurrent.CompletionException;
23 import java.util.concurrent.CompletionStage;
24 import java.util.concurrent.locks.LockSupport;
25
26 /**
27 * A {@link Future} that may be explicitly completed (setting its
28 * value and status), and may be used as a {@link CompletionStage},
29 * supporting dependent functions and actions that trigger upon its
30 * completion.
31 *
32 * <p>When two or more threads attempt to
33 * {@link #complete complete},
34 * {@link #completeExceptionally completeExceptionally}, or
35 * {@link #cancel cancel}
36 * a CompletableFuture, only one of them succeeds.
37 *
38 * <p>In addition to these and related methods for directly
39 * manipulating status and results, CompletableFuture implements
40 * interface {@link CompletionStage} with the following policies: <ul>
41 *
42 * <li>Actions supplied for dependent completions of
43 * <em>non-async</em> methods may be performed by the thread that
44 * completes the current CompletableFuture, or by any other caller of
45 * a completion method.</li>
46 *
47 * <li>All <em>async</em> methods without an explicit Executor
48 * argument are performed using the {@link ForkJoinPool#commonPool()}
49 * (unless it does not support a parallelism level of at least two, in
50 * which case, a new Thread is created to run each task). To simplify
51 * monitoring, debugging, and tracking, all generated asynchronous
52 * tasks are instances of the marker interface {@link
53 * AsynchronousCompletionTask}. </li>
54 *
55 * <li>All CompletionStage methods are implemented independently of
56 * other public methods, so the behavior of one method is not impacted
57 * by overrides of others in subclasses. </li> </ul>
58 *
59 * <p>CompletableFuture also implements {@link Future} with the following
60 * policies: <ul>
61 *
62 * <li>Since (unlike {@link FutureTask}) this class has no direct
63 * control over the computation that causes it to be completed,
64 * cancellation is treated as just another form of exceptional
65 * completion. Method {@link #cancel cancel} has the same effect as
66 * {@code completeExceptionally(new CancellationException())}. Method
67 * {@link #isCompletedExceptionally} can be used to determine if a
68 * CompletableFuture completed in any exceptional fashion.</li>
69 *
70 * <li>In case of exceptional completion with a CompletionException,
71 * methods {@link #get()} and {@link #get(long, TimeUnit)} throw an
72 * {@link ExecutionException} with the same cause as held in the
73 * corresponding CompletionException. To simplify usage in most
74 * contexts, this class also defines methods {@link #join()} and
75 * {@link #getNow} that instead throw the CompletionException directly
76 * in these cases.</li> </ul>
77 *
78 * @author Doug Lea
79 * @since 1.8
80 */
81 public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {
82
83 /*
84 * Overview:
85 *
86 * A CompletableFuture may have dependent completion actions,
87 * collected in a linked stack. It atomically completes by CASing
88 * a result field, and then pops off and runs those actions. This
89 * applies across normal vs exceptional outcomes, sync vs async
90 * actions, binary triggers, and various forms of completions.
91 *
92 * Non-nullness of field result (set via CAS) indicates done. An
93 * AltResult is used to box null as a result, as well as to hold
94 * exceptions. Using a single field makes completion simple to
95 * detect and trigger. Encoding and decoding is straightforward
96 * but adds to the sprawl of trapping and associating exceptions
97 * with targets. Minor simplifications rely on (static) NIL (to
98 * box null results) being the only AltResult with a null
99 * exception field, so we don't usually need explicit comparisons.
100 * Even though some of the generics casts are unchecked (see
101 * SuppressWarnings annotations), they are placed to be
102 * appropriate even if checked.
103 *
104 * Dependent actions are represented by Completion objects linked
105 * as Treiber stacks headed by field "stack". There are Completion
106 * classes for each kind of action, grouped into single-input
107 * (UniCompletion), two-input (BiCompletion), projected
108 * (BiCompletions using either (not both) of two inputs), shared
109 * (CoCompletion, used by the second of two sources), zero-input
110 * source actions, and Signallers that unblock waiters. Class
111 * Completion extends ForkJoinTask to enable async execution
112 * (adding no space overhead because we exploit its "tag" methods
113 * to maintain claims). It is also declared as Runnable to allow
114 * usage with arbitrary executors.
115 *
116 * Support for each kind of CompletionStage relies on a separate
117 * class, along with two CompletableFuture methods:
118 *
119 * * A Completion class with name X corresponding to function,
120 * prefaced with "Uni", "Bi", or "Or". Each class contains
121 * fields for source(s), actions, and dependent. They are
122 * boringly similar, differing from others only with respect to
123 * underlying functional forms. We do this so that users don't
124 * encounter layers of adaptors in common usages. We also
125 * include "Relay" classes/methods that don't correspond to user
126 * methods; they copy results from one stage to another.
127 *
128 * * Boolean CompletableFuture method x(...) (for example
129 * uniApply) takes all of the arguments needed to check that an
130 * action is triggerable, and then either runs the action or
131 * arranges its async execution by executing its Completion
132 * argument, if present. The method returns true if known to be
133 * complete.
134 *
135 * * Completion method tryFire(int mode) invokes the associated x
136 * method with its held arguments, and on success cleans up.
137 * The mode argument allows exec to be called twice (SYNC, then
138 * ASYNC); the first to screen and trap exceptions while
139 * arranging to execute, and the second when called from a
140 * task. (A few classes are not used async so take slightly
141 * different forms.) The claim() callback suppresses function
142 * invocation if already claimed by another thread.
143 *
144 * * CompletableFuture method xStage(...) is called from a public
145 * stage method of CompletableFuture x. It screens user
146 * arguments and invokes and/or creates the stage object. If
147 * not async and x is already complete, the action is run
148 * immediately. Otherwise a Completion c is created, pushed to
149 * x's stack (unless done), and started or triggered via
150 * c.tryFire. This also covers races possible if x completes
151 * while pushing. Classes with two inputs (for example BiApply)
152 * deal with races across both while pushing actions. The
153 * second completion is a CoCompletion pointing to the first,
154 * shared so that at most one performs the action. The
155 * multiple-arity methods allOf and anyOf do this pairwise to
156 * form trees of completions.
157 *
158 * Note that the generic type parameters of methods vary according
159 * to whether "this" is a source, dependent, or completion.
160 *
161 * Method postComplete is called upon completion unless the target
162 * is guaranteed not to be observable (i.e., not yet returned or
163 * linked). Multiple threads can call postComplete, which
164 * atomically pops each dependent action, and tries to trigger it
165 * via method exec. Triggering can propagate recursively, so exec
166 * in NESTED mode returns its completed dependent (if one exists)
167 * for further processing by its caller (see method postFire).
168 *
169 * Blocking methods get() and join() rely on Signaller Completions
170 * that wake up waiting threads. The mechanics are similar to
171 * Treiber stack wait-nodes used in FutureTask, Phaser, and
172 * SynchronousQueue. See their internal documentation for
173 * algorithmic details.
174 *
175 * Without precautions, CompletableFutures would be prone to
176 * garbage accumulation as chains of Completions build up, each
177 * pointing back to its sources. So we null out fields as soon as
178 * possible (see especially method Completion.detach). The
179 * screening checks needed anyway harmlessly ignore null arguments
180 * that may have been obtained during races with threads nulling
181 * out fields. We also try to unlink fired Completions from
182 * stacks that might never be popped (see method postFire).
183 * Completion fields need not be declared as final or volatile
184 * because they are only visible to other threads upon safe
185 * publication.
186 */
187
188 volatile Object result; // Either the result or boxed AltResult
189 volatile Completion stack; // Top of Treiber stack of dependent actions
190
191 final boolean internalComplete(Object r) { // CAS from null to r
192 return UNSAFE.compareAndSwapObject(this, RESULT, null, r);
193 }
194
195 final boolean casStack(Completion cmp, Completion val) {
196 return UNSAFE.compareAndSwapObject(this, STACK, cmp, val);
197 }
198
199 /* ------------- Encoding and decoding outcomes -------------- */
200
201 static final class AltResult { // See above
202 final Throwable ex; // null only for NIL
203 AltResult(Throwable x) { this.ex = x; }
204 }
205
206 static final AltResult NIL = new AltResult(null);
207
208 /**
209 * Returns the encoding of the given (non-null) exception as a
210 * wrapped CompletionException unless it is one already.
211 */
212 static AltResult encodeThrowable(Throwable x) {
213 return new AltResult((x instanceof CompletionException) ? x :
214 new CompletionException(x));
215 }
216
217 /**
218 * Returns the encoding of the given arguments: if the exception
219 * is non-null, encodes as AltResult. Otherwise uses the given
220 * value, boxed as NIL if null.
221 */
222 static Object encodeOutcome(Object v, Throwable x) {
223 return (x == null) ? (v == null) ? NIL : v : encodeThrowable(x);
224 }
225
226 /**
227 * Returns the encoding of a copied outcome; if exceptional,
228 * rewraps as a CompletionException, else returns argument.
229 */
230 static Object encodeRelay(Object r) {
231 Throwable x;
232 return (((r instanceof AltResult) &&
233 (x = ((AltResult)r).ex) != null &&
234 !(x instanceof CompletionException)) ?
235 new AltResult(new CompletionException(x)) : r);
236 }
237
238 /**
239 * Reports result using Future.get conventions.
240 */
241 private static <T> T reportGet(Object r)
242 throws InterruptedException, ExecutionException {
243 if (r == null) // by convention below, null means interrupted
244 throw new InterruptedException();
245 if (r instanceof AltResult) {
246 Throwable x, cause;
247 if ((x = ((AltResult)r).ex) == null)
248 return null;
249 if (x instanceof CancellationException)
250 throw (CancellationException)x;
251 if ((x instanceof CompletionException) &&
252 (cause = x.getCause()) != null)
253 x = cause;
254 throw new ExecutionException(x);
255 }
256 @SuppressWarnings("unchecked") T t = (T) r;
257 return t;
258 }
259
260 /**
261 * Decodes outcome to return result or throw unchecked exception.
262 */
263 private static <T> T reportJoin(Object r) {
264 if (r instanceof AltResult) {
265 Throwable x;
266 if ((x = ((AltResult)r).ex) == null)
267 return null;
268 if (x instanceof CancellationException)
269 throw (CancellationException)x;
270 if (x instanceof CompletionException)
271 throw (CompletionException)x;
272 throw new CompletionException(x);
273 }
274 @SuppressWarnings("unchecked") T t = (T) r;
275 return t;
276 }
277
278 /* ------------- Async task preliminaries -------------- */
279
280 /**
281 * A marker interface identifying asynchronous tasks produced by
282 * {@code async} methods. This may be useful for monitoring,
283 * debugging, and tracking asynchronous activities.
284 *
285 * @since 1.8
286 */
287 public static interface AsynchronousCompletionTask {
288 }
289
290 /**
291 * Default executor -- ForkJoinPool.commonPool() unless it cannot
292 * support parallelism.
293 */
294 static final Executor asyncPool =
295 (ForkJoinPool.getCommonPoolParallelism() > 1) ?
296 ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
297
298 /** Fallback if ForkJoinPool.commonPool() cannot support parallelism */
299 static final class ThreadPerTaskExecutor implements Executor {
300 public void execute(Runnable r) { new Thread(r).start(); }
301 }
302
303 /**
304 * Null-checks user executor argument, and translates uses of
305 * commonPool to asyncPool in case parallelism disabled.
306 */
307 static Executor screenExecutor(Executor e) {
308 if (e == null) throw new NullPointerException();
309 return (e == ForkJoinPool.commonPool()) ? asyncPool : e;
310 }
311
312 // Modes for Completion.exec. Signedness matters.
313 static final int SYNC = 0;
314 static final int ASYNC = 1;
315 static final int NESTED = -1;
316
317 /* ------------- Base Completion classes and operations -------------- */
318
319 @SuppressWarnings("serial")
320 abstract static class Completion extends ForkJoinTask<Void>
321 implements Runnable, AsynchronousCompletionTask {
322 volatile Completion next; // Treiber stack link
323
324 /**
325 * Performs completion action if triggered, returning a
326 * dependent that may need propagation, if one exists.
327 *
328 * @param mode SYNC, ASYNC, or NESTED
329 */
330 abstract CompletableFuture<?> tryFire(int mode);
331
332 /** Returns true if possibly still triggerable. Used by cleanStack. */
333 abstract boolean isLive();
334
335 public final void run() { tryFire(ASYNC); }
336 public final boolean exec() { tryFire(ASYNC); return true; }
337 public final Void getRawResult() { return null; }
338 public final void setRawResult(Void v) {}
339 }
340
341 /**
342 * Pops and tries to trigger all reachable dependents. Call only
343 * when known to be done.
344 */
345 final void postComplete() {
346 /*
347 * On each step, variable f holds current dependents to pop
348 * and run. It is extended along only one path at a time,
349 * pushing others to avoid unbounded recursion.
350 */
351 CompletableFuture<?> f = this; Completion h;
352 while ((h = f.stack) != null ||
353 (f != this && (h = (f = this).stack) != null)) {
354 CompletableFuture<?> d; Completion t;
355 if (f.casStack(h, t = h.next)) {
356 if (t != null) {
357 if (f != this) { // push
358 do {} while (!casStack(h.next = stack, h));
359 continue;
360 }
361 h.next = null; // detach
362 }
363 f = (d = h.tryFire(NESTED)) == null ? this : d;
364 }
365 }
366 }
367
368 /** Traverses stack and unlinks dead Completions. */
369 final void cleanStack() {
370 for (Completion p = null, q = stack; q != null;) {
371 Completion s = q.next;
372 if (q.isLive()) {
373 p = q;
374 q = s;
375 }
376 else if (p == null) {
377 casStack(q, s);
378 q = stack;
379 }
380 else {
381 p.next = s;
382 if (p.isLive())
383 q = s;
384 else {
385 p = null; // restart
386 q = stack;
387 }
388 }
389 }
390 }
391
392 /* ------------- One-input Completions -------------- */
393
394 /** A Completion with a source, dependent, and executor. */
395 @SuppressWarnings("serial")
396 abstract static class UniCompletion<T> extends Completion {
397 Executor executor; // executor to use (null if none)
398 CompletableFuture<T> dep; // the dependent to complete
399 CompletableFuture<?> src; // source for action
400
401 UniCompletion(Executor executor, CompletableFuture<T> dep,
402 CompletableFuture<?> src) {
403 this.executor = executor; this.dep = dep; this.src = src;
404 }
405
406 /**
407 * Returns true if action can be run. Call only when known to
408 * be triggerable. Uses FJ tag bit to ensure that only one
409 * thread claims ownership. If async, starts as task -- a
410 * later call to tryFire will run action.
411 */
412 final boolean claim() {
413 Executor e = executor;
414 if (compareAndSetForkJoinTaskTag((short)0, (short)1)) {
415 if (e == null)
416 return true;
417 executor = null; // disable
418 e.execute(this);
419 }
420 return false;
421 }
422
423 final boolean isLive() { return dep != null; }
424 }
425
426 /** Pushes the given completion (if it exists) unless done. */
427 final void push(UniCompletion<?> c) {
428 if (c != null) {
429 while (result == null && !casStack(c.next = stack, c))
430 c.next = null; // clear on failure
431 }
432 }
433
434 /**
435 * Post-processing by dependent after successful UniCompletion
436 * tryFire. Tries to clean stack of source a, and then either runs
437 * postComplete or returns this to caller, depending on mode.
438 */
439 final CompletableFuture<T> postFire(CompletableFuture<?> a, int mode) {
440 if (a != null && a.stack != null) {
441 if (mode < 0 || a.result == null)
442 a.cleanStack();
443 else
444 a.postComplete();
445 }
446 if (result != null && stack != null) {
447 if (mode < 0)
448 return this;
449 else
450 postComplete();
451 }
452 return null;
453 }
454
455 @SuppressWarnings("serial")
456 static final class UniApply<T,U> extends UniCompletion<U> {
457 Function<? super T,? extends U> fn;
458 UniApply(Executor executor, CompletableFuture<U> dep,
459 CompletableFuture<?> src, Function<? super T,? extends U> fn) {
460 super(executor, dep, src); this.fn = fn;
461 }
462 final CompletableFuture<?> tryFire(int mode) {
463 CompletableFuture<U> d; CompletableFuture<?> a;
464 if ((d = dep) == null ||
465 !d.uniApply(a = src, fn, mode > 0 ? null : this))
466 return null;
467 dep = null; src = null; fn = null;
468 return d.postFire(a, mode);
469 }
470 }
471
472 final <S> boolean uniApply(CompletableFuture<?> a,
473 Function<? super S,? extends T> f,
474 UniApply<S,T> c) {
475 Object r; T u; Throwable x;
476 if (a == null || (r = a.result) == null || f == null)
477 return false;
478 if (result == null) {
479 try {
480 if (r instanceof AltResult) {
481 x = ((AltResult)r).ex;
482 r = null;
483 }
484 else
485 x = null;
486 if (x != null)
487 u = null;
488 else if (c != null && !c.claim())
489 return false;
490 else {
491 @SuppressWarnings("unchecked") S t = (S) r;
492 u = f.apply(t);
493 }
494 } catch (Throwable ex) {
495 x = ex;
496 u = null;
497 }
498 internalComplete(encodeOutcome(u, x));
499 }
500 return true;
501 }
502
503 private <U> CompletableFuture<U> uniApplyStage(
504 Executor e, Function<? super T,? extends U> f) {
505 if (f == null) throw new NullPointerException();
506 CompletableFuture<U> d = new CompletableFuture<U>();
507 if (e != null || !d.uniApply(this, f, null)) {
508 UniApply<T,U> c = new UniApply<T,U>(e, d, this, f);
509 push(c);
510 c.tryFire(SYNC);
511 }
512 return d;
513 }
514
515 @SuppressWarnings("serial")
516 static final class UniAccept<T> extends UniCompletion<Void> {
517 Consumer<? super T> fn;
518 UniAccept(Executor executor, CompletableFuture<Void> dep,
519 CompletableFuture<?> src, Consumer<? super T> fn) {
520 super(executor, dep, src); this.fn = fn;
521 }
522 final CompletableFuture<?> tryFire(int mode) {
523 CompletableFuture<Void> d; CompletableFuture<?> a;
524 if ((d = dep) == null ||
525 !d.uniAccept(a = src, fn, mode > 0 ? null : this))
526 return null;
527 dep = null; src = null; fn = null;
528 return d.postFire(a, mode);
529 }
530 }
531
532 final <S> boolean uniAccept(CompletableFuture<?> a,
533 Consumer<? super S> f, UniAccept<S> c) {
534 Object r; Throwable x;
535 if (a == null || (r = a.result) == null || f == null)
536 return false;
537 if (result == null) {
538 try {
539 if (r instanceof AltResult) {
540 x = ((AltResult)r).ex;
541 r = null;
542 }
543 else
544 x = null;
545 if (x == null) {
546 if (c != null && !c.claim())
547 return false;
548 else {
549 @SuppressWarnings("unchecked") S t = (S) r;
550 f.accept(t);
551 }
552 }
553 } catch (Throwable ex) {
554 x = ex;
555 }
556 internalComplete(encodeOutcome(null, x));
557 }
558 return true;
559 }
560
561 private CompletableFuture<Void> uniAcceptStage(Executor e,
562 Consumer<? super T> f) {
563 if (f == null) throw new NullPointerException();
564 CompletableFuture<Void> d = new CompletableFuture<Void>();
565 if (e != null || !d.uniAccept(this, f, null)) {
566 UniAccept<T> c = new UniAccept<T>(e, d, this, f);
567 push(c);
568 c.tryFire(SYNC);
569 }
570 return d;
571 }
572
573 @SuppressWarnings("serial")
574 static final class UniRun extends UniCompletion<Void> {
575 Runnable fn;
576 UniRun(Executor executor, CompletableFuture<Void> dep,
577 CompletableFuture<?> src, Runnable fn) {
578 super(executor, dep, src); this.fn = fn;
579 }
580 final CompletableFuture<?> tryFire(int mode) {
581 CompletableFuture<Void> d; CompletableFuture<?> a;
582 if ((d = dep) == null ||
583 !d.uniRun(a = src, fn, mode > 0 ? null : this))
584 return null;
585 dep = null; src = null; fn = null;
586 return d.postFire(a, mode);
587 }
588 }
589
590 final boolean uniRun(CompletableFuture<?> a, Runnable f, UniRun c) {
591 Object r; Throwable x;
592 if (a == null || (r = a.result) == null || f == null)
593 return false;
594 if (result == null) {
595 try {
596 if (r instanceof AltResult)
597 x = ((AltResult)r).ex;
598 else
599 x = null;
600 if (x == null) {
601 if (c != null && !c.claim())
602 return false;
603 else
604 f.run();
605 }
606 } catch (Throwable ex) {
607 x = ex;
608 }
609 internalComplete(encodeOutcome(null, x));
610 }
611 return true;
612 }
613
614 private CompletableFuture<Void> uniRunStage(Executor e, Runnable f) {
615 if (f == null) throw new NullPointerException();
616 CompletableFuture<Void> d = new CompletableFuture<Void>();
617 if (e != null || !d.uniRun(this, f, null)) {
618 UniRun c = new UniRun(e, d, this, f);
619 push(c);
620 c.tryFire(SYNC);
621 }
622 return d;
623 }
624
625 @SuppressWarnings("serial")
626 static final class UniWhenComplete<T> extends UniCompletion<T> {
627 BiConsumer<? super T, ? super Throwable> fn;
628 UniWhenComplete(Executor executor, CompletableFuture<T> dep,
629 CompletableFuture<?> src,
630 BiConsumer<? super T, ? super Throwable> fn) {
631 super(executor, dep, src); this.fn = fn;
632 }
633 final CompletableFuture<?> tryFire(int mode) {
634 CompletableFuture<T> d; CompletableFuture<?> a;
635 if ((d = dep) == null ||
636 !d.uniWhenComplete(a = src, fn, mode > 0 ? null : this))
637 return null;
638 dep = null; src = null; fn = null;
639 return d.postFire(a, mode);
640 }
641 }
642
643 final boolean uniWhenComplete(CompletableFuture<?> a,
644 BiConsumer<? super T,? super Throwable> f,
645 UniWhenComplete<T> c) {
646 Object r;
647 if (a == null || (r = a.result) == null || f == null)
648 return false;
649 if (result == null) {
650 Throwable x = null, y = null;
651 try {
652 if (r instanceof AltResult) {
653 x = ((AltResult)r).ex;
654 r = null;
655 }
656 if (c != null && !c.claim())
657 return false;
658 else {
659 @SuppressWarnings("unchecked") T t = (T) r;
660 f.accept(t, x);
661 }
662 } catch (Throwable ex) {
663 y = ex;
664 }
665 internalComplete(encodeOutcome(r, x != null ? x : y));
666 }
667 return true;
668 }
669
670 private CompletableFuture<T> uniWhenCompleteStage(
671 Executor e, BiConsumer<? super T, ? super Throwable> f) {
672 if (f == null) throw new NullPointerException();
673 CompletableFuture<T> d = new CompletableFuture<T>();
674 if (e != null || !d.uniWhenComplete(this, f, null)) {
675 UniWhenComplete<T> c = new UniWhenComplete<T>(e, d, this, f);
676 push(c);
677 c.tryFire(SYNC);
678 }
679 return d;
680 }
681
682 @SuppressWarnings("serial")
683 static final class UniHandle<T,U> extends UniCompletion<U> {
684 BiFunction<? super T, Throwable, ? extends U> fn;
685 UniHandle(Executor executor, CompletableFuture<U> dep,
686 CompletableFuture<?> src,
687 BiFunction<? super T, Throwable, ? extends U> fn) {
688 super(executor, dep, src); this.fn = fn;
689 }
690 final CompletableFuture<?> tryFire(int mode) {
691 CompletableFuture<U> d; CompletableFuture<?> a;
692 if ((d = dep) == null ||
693 !d.uniHandle(a = src, fn, mode > 0 ? null : this))
694 return null;
695 dep = null; src = null; fn = null;
696 return d.postFire(a, mode);
697 }
698 }
699
700 final <S> boolean uniHandle(CompletableFuture<?> a,
701 BiFunction<? super S, Throwable, ? extends T> f,
702 UniHandle<S,T> c) {
703 Object r; T u; Throwable x, y;
704 if (a == null || (r = a.result) == null || f == null)
705 return false;
706 if (result == null) {
707 try {
708 if (r instanceof AltResult) {
709 x = ((AltResult)r).ex;
710 r = null;
711 }
712 else
713 x = null;
714 if (c != null && !c.claim())
715 return false;
716 else {
717 @SuppressWarnings("unchecked") S t = (S) r;
718 u = f.apply(t, x);
719 y = null;
720 }
721 } catch (Throwable ex) {
722 y = ex;
723 u = null;
724 }
725 internalComplete(encodeOutcome(u, y));
726 }
727 return true;
728 }
729
730 private <U> CompletableFuture<U> uniHandleStage(
731 Executor e, BiFunction<? super T, Throwable, ? extends U> f) {
732 if (f == null) throw new NullPointerException();
733 CompletableFuture<U> d = new CompletableFuture<U>();
734 if (e != null || !d.uniHandle(this, f, null)) {
735 UniHandle<T,U> c = new UniHandle<T,U>(e, d, this, f);
736 push(c);
737 c.tryFire(SYNC);
738 }
739 return d;
740 }
741
742 @SuppressWarnings("serial")
743 static final class UniExceptionally<T> extends UniCompletion<T> {
744 Function<? super Throwable, ? extends T> fn;
745 UniExceptionally(CompletableFuture<T> dep, CompletableFuture<?> src,
746 Function<? super Throwable, ? extends T> fn) {
747 super(null, dep, src); this.fn = fn;
748 }
749 final CompletableFuture<?> tryFire(int mode) { // never ASYNC
750 CompletableFuture<T> d; CompletableFuture<?> a;
751 if ((d = dep) == null || !d.uniExceptionally(a = src, fn, this))
752 return null;
753 dep = null; src = null; fn = null;
754 return d.postFire(a, mode);
755 }
756 }
757
758 final boolean uniExceptionally(CompletableFuture<?> a,
759 Function<? super Throwable, ? extends T> f,
760 UniExceptionally<T> c) {
761 Object r; T t; Throwable x, y;
762 if (a == null || (r = a.result) == null || f == null)
763 return false;
764 if (r instanceof AltResult)
765 x = ((AltResult)r).ex;
766 else
767 x = null;
768 if (result == null) {
769 try {
770 if (c != null && !c.claim())
771 return false;
772 else if (x == null) {
773 @SuppressWarnings("unchecked") T tr = (T) r;
774 t = tr;
775 y = null;
776 }
777 else {
778 t = f.apply(x);
779 y = null;
780 }
781 } catch (Throwable ex) {
782 y = ex;
783 t = null;
784 }
785 internalComplete(encodeOutcome(t, y));
786 }
787 return true;
788 }
789
790 private CompletableFuture<T> uniExceptionallyStage(
791 Function<Throwable, ? extends T> f) {
792 if (f == null) throw new NullPointerException();
793 CompletableFuture<T> d = new CompletableFuture<T>();
794 if (!d.uniExceptionally(this, f, null)) {
795 UniExceptionally<T> c = new UniExceptionally<T>(d, this, f);
796 push(c);
797 c.tryFire(SYNC);
798 }
799 return d;
800 }
801
802 @SuppressWarnings("serial")
803 static final class UniRelay<T> extends UniCompletion<T> { // for Compose
804 UniRelay(CompletableFuture<T> dep, CompletableFuture<?> src) {
805 super(null, dep, src);
806 }
807 final CompletableFuture<?> tryFire(int mode) {
808 CompletableFuture<T> d; CompletableFuture<?> a;
809 if ((d = dep) == null || !d.uniRelay(a = src))
810 return null;
811 src = null; dep = null;
812 return d.postFire(a, mode);
813 }
814 }
815
816 final boolean uniRelay(CompletableFuture<?> a) {
817 Object r;
818 if (a == null || (r = a.result) == null)
819 return false;
820 Object s = encodeRelay(r);
821 if (result == null) // no need to claim
822 internalComplete(s);
823 return true;
824 }
825
826 @SuppressWarnings("serial")
827 static final class UniCompose<T,U> extends UniCompletion<U> {
828 Function<? super T, ? extends CompletionStage<U>> fn;
829 UniCompose(Executor executor, CompletableFuture<U> dep,
830 CompletableFuture<?> src,
831 Function<? super T, ? extends CompletionStage<U>> fn) {
832 super(executor, dep, src); this.fn = fn;
833 }
834 final CompletableFuture<?> tryFire(int mode) {
835 CompletableFuture<U> d; CompletableFuture<?> a;
836 if ((d = dep) == null ||
837 !d.uniCompose(a = src, fn, mode > 0 ? null : this))
838 return null;
839 dep = null; src = null; fn = null;
840 return d.postFire(a, mode);
841 }
842 }
843
844 final <S> boolean uniCompose(
845 CompletableFuture<?> a,
846 Function<? super S, ? extends CompletionStage<T>> f,
847 UniCompose<S,T> c) {
848 Object r; Throwable x;
849 if (a == null || (r = a.result) == null || f == null)
850 return false;
851 if (result == null) {
852 try {
853 if (r instanceof AltResult) {
854 x = ((AltResult)r).ex;
855 r = null;
856 }
857 else
858 x = null;
859 if (x == null) {
860 if (c != null && !c.claim())
861 return false;
862 else {
863 @SuppressWarnings("unchecked") S t = (S) r;
864 CompletableFuture<T> g =
865 f.apply(t).toCompletableFuture();
866 if (g.result == null || !uniRelay(g)) {
867 UniRelay<T> copy = new UniRelay<T>(this, g);
868 g.push(copy);
869 copy.tryFire(SYNC);
870 if (result == null)
871 return false;
872 }
873 }
874 }
875 } catch (Throwable ex) {
876 x = ex;
877 }
878 if (x != null)
879 internalComplete(encodeOutcome(null, x));
880 }
881 return true;
882 }
883
884 private <U> CompletableFuture<U> uniComposeStage(
885 Executor e, Function<? super T, ? extends CompletionStage<U>> f) {
886 if (f == null) throw new NullPointerException();
887 Object r; Throwable x;
888 if (e == null && (r = result) != null) {
889 try { // try to return function result
890 if (r instanceof AltResult) {
891 x = ((AltResult)r).ex;
892 r = null;
893 }
894 else
895 x = null;
896 if (x == null) {
897 @SuppressWarnings("unchecked") T t = (T) r;
898 return f.apply(t).toCompletableFuture();
899 }
900 } catch (Throwable ex) {
901 x = ex;
902 }
903 }
904 else
905 x = null;
906 CompletableFuture<U> d = new CompletableFuture<U>();
907 if (x == null) {
908 UniCompose<T,U> c = new UniCompose<T,U>(e, d, this, f);
909 push(c);
910 c.tryFire(SYNC);
911 }
912 else
913 d.result = encodeOutcome(null, x);
914 return d;
915 }
916
917 /* ------------- Two-input Completions -------------- */
918
919 /** A Completion for an action with two sources */
920 @SuppressWarnings("serial")
921 abstract static class BiCompletion<T> extends UniCompletion<T> {
922 CompletableFuture<?> snd; // second source for action
923 BiCompletion(Executor executor, CompletableFuture<T> dep,
924 CompletableFuture<?> src, CompletableFuture<?> snd) {
925 super(executor, dep, src); this.snd = snd;
926 }
927 }
928
929 /** A Completion delegating to a BiCompletion */
930 @SuppressWarnings("serial")
931 static final class CoCompletion extends Completion {
932 BiCompletion<?> base;
933 CoCompletion(BiCompletion<?> base) { this.base = base; }
934 final CompletableFuture<?> tryFire(int mode) {
935 BiCompletion<?> c; CompletableFuture<?> d;
936 if ((c = base) == null || (d = c.tryFire(mode)) == null)
937 return null;
938 base = null; // detach
939 return d;
940 }
941 final boolean isLive() {
942 BiCompletion<?> c;
943 return (c = base) != null && c.dep != null;
944 }
945 }
946
947 /** Pushes completion to this and b unless both done. */
948 final void bipush(CompletableFuture<?> b, BiCompletion<?> c) {
949 if (c != null) {
950 Object r;
951 while ((r = result) == null && !casStack(c.next = stack, c))
952 c.next = null;
953 if (b != null && b != this && b.result == null) {
954 Completion q = (r != null) ? c : new CoCompletion(c);
955 while (b.result == null && !b.casStack(q.next = b.stack, q))
956 q.next = null;
957 }
958 }
959 }
960
961 /** Post-processing after successful BiCompletion tryFire. */
962 final CompletableFuture<T> postFire(CompletableFuture<?> a,
963 CompletableFuture<?> b, int mode) {
964 if (b != null && b.stack != null) { // clean second source
965 if (mode < 0 || b.result == null)
966 b.cleanStack();
967 else
968 b.postComplete();
969 }
970 return postFire(a, mode);
971 }
972
973 @SuppressWarnings("serial")
974 static final class BiApply<T,U,V> extends BiCompletion<V> {
975 BiFunction<? super T,? super U,? extends V> fn;
976 BiApply(Executor executor, CompletableFuture<V> dep,
977 CompletableFuture<?> src, CompletableFuture<?> snd,
978 BiFunction<? super T,? super U,? extends V> fn) {
979 super(executor, dep, src, snd); this.fn = fn;
980 }
981 final CompletableFuture<?> tryFire(int mode) {
982 CompletableFuture<V> d; CompletableFuture<?> a, b;
983 if ((d = dep) == null ||
984 !d.biApply(a = src, b = snd, fn, mode > 0 ? null : this))
985 return null;
986 dep = null; snd = src = null; fn = null;
987 return d.postFire(a, b, mode);
988 }
989 }
990
991 final <R,S> boolean biApply(CompletableFuture<?> a, CompletableFuture<?> b,
992 BiFunction<? super R,? super S,? extends T> f,
993 BiApply<R,S,T> c) {
994 Object r, s; T v; Throwable x;
995 if (a == null || (r = a.result) == null ||
996 b == null || (s = b.result) == null || f == null)
997 return false;
998 if (result == null) {
999 try {
1000 if (r instanceof AltResult) {
1001 x = ((AltResult)r).ex;
1002 r = null;
1003 }
1004 else
1005 x = null;
1006 if (x == null && (s instanceof AltResult)) {
1007 x = ((AltResult)s).ex;
1008 s = null;
1009 }
1010 if (x != null)
1011 v = null;
1012 else if (c != null && !c.claim())
1013 return false;
1014 else {
1015 @SuppressWarnings("unchecked") R t = (R) r;
1016 @SuppressWarnings("unchecked") S u = (S) s;
1017 v = f.apply(t, u);
1018 }
1019 } catch (Throwable ex) {
1020 x = ex;
1021 v = null;
1022 }
1023 internalComplete(encodeOutcome(v, x));
1024 }
1025 return true;
1026 }
1027
1028 private <U,V> CompletableFuture<V> biApplyStage(
1029 Executor e, CompletionStage<? extends U> o,
1030 BiFunction<? super T,? super U,? extends V> f) {
1031 CompletableFuture<?> b;
1032 if (f == null || (b = o.toCompletableFuture()) == null)
1033 throw new NullPointerException();
1034 CompletableFuture<V> d = new CompletableFuture<V>();
1035 if (e != null || !d.biApply(this, b, f, null)) {
1036 BiApply<T,U,V> c = new BiApply<T,U,V>(e, d, this, b, f);
1037 bipush(b, c);
1038 c.tryFire(SYNC);
1039 }
1040 return d;
1041 }
1042
1043 @SuppressWarnings("serial")
1044 static final class BiAccept<T,U> extends BiCompletion<Void> {
1045 BiConsumer<? super T,? super U> fn;
1046 BiAccept(Executor executor, CompletableFuture<Void> dep,
1047 CompletableFuture<?> src, CompletableFuture<?> snd,
1048 BiConsumer<? super T,? super U> fn) {
1049 super(executor, dep, src, snd); this.fn = fn;
1050 }
1051 final CompletableFuture<?> tryFire(int mode) {
1052 CompletableFuture<Void> d; CompletableFuture<?> a, b;
1053 if ((d = dep) == null ||
1054 !d.biAccept(a = src, b = snd, fn, mode > 0 ? null : this))
1055 return null;
1056 dep = null; snd = src = null; fn = null;
1057 return d.postFire(a, b, mode);
1058 }
1059 }
1060
1061 final <R,S> boolean biAccept(CompletableFuture<?> a, CompletableFuture<?> b,
1062 BiConsumer<? super R,? super S> f,
1063 BiAccept<R,S> c) {
1064 Object r, s; Throwable x;
1065 if (a == null || (r = a.result) == null ||
1066 b == null || (s = b.result) == null || f == null)
1067 return false;
1068 if (result == null) {
1069 try {
1070 if (r instanceof AltResult) {
1071 x = ((AltResult)r).ex;
1072 r = null;
1073 }
1074 else
1075 x = null;
1076 if (x == null && (s instanceof AltResult)) {
1077 x = ((AltResult)s).ex;
1078 s = null;
1079 }
1080 if (x == null) {
1081 if (c != null && !c.claim())
1082 return false;
1083 else {
1084 @SuppressWarnings("unchecked") R t = (R) r;
1085 @SuppressWarnings("unchecked") S u = (S) s;
1086 f.accept(t, u);
1087 }
1088 }
1089 } catch (Throwable ex) {
1090 x = ex;
1091 }
1092 internalComplete(encodeOutcome(null, x));
1093 }
1094 return true;
1095 }
1096
1097 private <U> CompletableFuture<Void> biAcceptStage(
1098 Executor e, CompletionStage<? extends U> o,
1099 BiConsumer<? super T,? super U> f) {
1100 CompletableFuture<?> b;
1101 if (f == null || (b = o.toCompletableFuture()) == null)
1102 throw new NullPointerException();
1103 CompletableFuture<Void> d = new CompletableFuture<Void>();
1104 if (e != null || !d.biAccept(this, b, f, null)) {
1105 BiAccept<T,U> c = new BiAccept<T,U>(e, d, this, b, f);
1106 bipush(b, c);
1107 c.tryFire(SYNC);
1108 }
1109 return d;
1110 }
1111
1112 @SuppressWarnings("serial")
1113 static final class BiRun extends BiCompletion<Void> {
1114 Runnable fn;
1115 BiRun(Executor executor, CompletableFuture<Void> dep,
1116 CompletableFuture<?> src, CompletableFuture<?> snd,
1117 Runnable fn) {
1118 super(executor, dep, src, snd); this.fn = fn;
1119 }
1120 final CompletableFuture<?> tryFire(int mode) {
1121 CompletableFuture<Void> d; CompletableFuture<?> a, b;
1122 if ((d = dep) == null ||
1123 !d.biRun(a = src, b = snd, fn, mode > 0 ? null : this))
1124 return null;
1125 dep = null; snd = src = null; fn = null;
1126 return d.postFire(a, b, mode);
1127 }
1128 }
1129
1130 final boolean biRun(CompletableFuture<?> a, CompletableFuture<?> b,
1131 Runnable f, BiRun c) {
1132 Object r, s; Throwable x;
1133 if (a == null || (r = a.result) == null ||
1134 b == null || (s = b.result) == null || f == null)
1135 return false;
1136 if (result == null) {
1137 try {
1138 if (r instanceof AltResult)
1139 x = ((AltResult)r).ex;
1140 else
1141 x = null;
1142 if (x == null && (s instanceof AltResult))
1143 x = ((AltResult)s).ex;
1144 if (x == null) {
1145 if (c != null && !c.claim())
1146 return false;
1147 else
1148 f.run();
1149 }
1150 } catch (Throwable ex) {
1151 x = ex;
1152 }
1153 internalComplete(encodeOutcome(null, x));
1154 }
1155 return true;
1156 }
1157
1158 private CompletableFuture<Void> biRunStage(Executor e, CompletionStage<?> o,
1159 Runnable f) {
1160 CompletableFuture<?> b;
1161 if (f == null || (b = o.toCompletableFuture()) == null)
1162 throw new NullPointerException();
1163 CompletableFuture<Void> d = new CompletableFuture<Void>();
1164 if (e != null || !d.biRun(this, b, f, null)) {
1165 BiRun c = new BiRun(e, d, this, b, f);
1166 bipush(b, c);
1167 c.tryFire(SYNC);
1168 }
1169 return d;
1170 }
1171
1172 @SuppressWarnings("serial")
1173 static final class BiRelay extends BiCompletion<Void> { // for And
1174 BiRelay(CompletableFuture<Void> dep, CompletableFuture<?> src,
1175 CompletableFuture<?> snd) {
1176 super(null, dep, src, snd);
1177 }
1178 final CompletableFuture<?> tryFire(int mode) {
1179 CompletableFuture<Void> d; CompletableFuture<?> a, b;
1180 if ((d = dep) == null || !d.biRelay(a = src, b = snd))
1181 return null;
1182 snd = src = null; dep = null;
1183 return d.postFire(a, b, mode);
1184 }
1185 }
1186
1187 private boolean biRelay(CompletableFuture<?> a, CompletableFuture<?> b) {
1188 Object r, s; Throwable x;
1189 if (a == null || (r = a.result) == null ||
1190 b == null || (s = b.result) == null)
1191 return false;
1192 if (result == null) {
1193 if (r instanceof AltResult)
1194 x = ((AltResult)r).ex;
1195 else
1196 x = null;
1197 if (x == null && (s instanceof AltResult))
1198 x = ((AltResult)s).ex;
1199 internalComplete(encodeOutcome(null, x));
1200 }
1201 return true;
1202 }
1203
1204 /** Recursively constructs a tree of completions */
1205 static CompletableFuture<Void> andTree(CompletableFuture<?>[] cfs,
1206 int lo, int hi) {
1207 CompletableFuture<Void> d = new CompletableFuture<Void>();
1208 if (lo > hi) // empty
1209 d.result = NIL;
1210 else {
1211 CompletableFuture<?> a, b;
1212 int mid = (lo + hi) >>> 1;
1213 if ((a = (lo == mid ? cfs[lo] :
1214 andTree(cfs, lo, mid))) == null ||
1215 (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
1216 andTree(cfs, mid+1, hi))) == null)
1217 throw new NullPointerException();
1218 if (!d.biRelay(a, b)) {
1219 BiRelay c = new BiRelay(d, a, b);
1220 a.bipush(b, c);
1221 c.tryFire(SYNC);
1222 }
1223 }
1224 return d;
1225 }
1226
1227 /* ------------- Projected (Ored) BiCompletions -------------- */
1228
1229 /** Pushes completion to this and b unless either done. */
1230 final void orpush(CompletableFuture<?> b, BiCompletion<?> c) {
1231 if (c != null) {
1232 while ((b == null || b.result == null) && result == null) {
1233 if (casStack(c.next = stack, c)) {
1234 if (b != null && b != this && b.result == null) {
1235 Completion q = new CoCompletion(c);
1236 while (result == null && b.result == null &&
1237 !b.casStack(q.next = b.stack, q))
1238 q.next = null;
1239 }
1240 break;
1241 }
1242 c.next = null;
1243 }
1244 }
1245 }
1246
1247 @SuppressWarnings("serial")
1248 static final class OrApply<T,U> extends BiCompletion<U> {
1249 Function<? super T,? extends U> fn;
1250 OrApply(Executor executor, CompletableFuture<U> dep,
1251 CompletableFuture<?> src, CompletableFuture<?> snd,
1252 Function<? super T,? extends U> fn) {
1253 super(executor, dep, src, snd); this.fn = fn;
1254 }
1255 final CompletableFuture<?> tryFire(int mode) {
1256 CompletableFuture<U> d; CompletableFuture<?> a, b;
1257 if ((d = dep) == null ||
1258 !d.orApply(a = src, b = snd, fn, mode > 0 ? null : this))
1259 return null;
1260 dep = null; snd = src = null; fn = null;
1261 return d.postFire(a, b, mode);
1262 }
1263 }
1264
1265 final <S> boolean orApply(CompletableFuture<?> a, CompletableFuture<?> b,
1266 Function<? super S, ? extends T> f,
1267 OrApply<S,T> c) {
1268 Object r; T u; Throwable x;
1269 if (a == null || b == null ||
1270 ((r = a.result) == null && (r = b.result) == null) || f == null)
1271 return false;
1272 if (result == null) {
1273 try {
1274 if (r instanceof AltResult) {
1275 x = ((AltResult)r).ex;
1276 r = null;
1277 }
1278 else
1279 x = null;
1280 if (x != null)
1281 u = null;
1282 else if (c != null && !c.claim())
1283 return false;
1284 else {
1285 @SuppressWarnings("unchecked") S t = (S) r;
1286 u = f.apply(t);
1287 }
1288 } catch (Throwable ex) {
1289 x = ex;
1290 u = null;
1291 }
1292 internalComplete(encodeOutcome(u, x));
1293 }
1294 return true;
1295 }
1296
1297 private <T,U> CompletableFuture<U> orApplyStage(
1298 Executor e, CompletionStage<? extends T> o, Function<? super T, U> f) {
1299 CompletableFuture<?> b;
1300 if (f == null || (b = o.toCompletableFuture()) == null)
1301 throw new NullPointerException();
1302 CompletableFuture<U> d = new CompletableFuture<U>();
1303 if (e != null || !d.orApply(this, b, f, null)) {
1304 OrApply<T,U> c = new OrApply<T,U>(e, d, this, b, f);
1305 orpush(b, c);
1306 c.tryFire(SYNC);
1307 }
1308 return d;
1309 }
1310
1311 @SuppressWarnings("serial")
1312 static final class OrAccept<T> extends BiCompletion<Void> {
1313 Consumer<? super T> fn;
1314 OrAccept(Executor executor, CompletableFuture<Void> dep,
1315 CompletableFuture<?> src, CompletableFuture<?> snd,
1316 Consumer<? super T> fn) {
1317 super(executor, dep, src, snd); this.fn = fn;
1318 }
1319 final CompletableFuture<?> tryFire(int mode) {
1320 CompletableFuture<Void> d; CompletableFuture<?> a, b;
1321 if ((d = dep) == null ||
1322 !d.orAccept(a = src, b = snd, fn, mode > 0 ? null : this))
1323 return null;
1324 dep = null; snd = src = null; fn = null;
1325 return d.postFire(a, b, mode);
1326 }
1327 }
1328
1329 final <S> boolean orAccept(CompletableFuture<?> a,
1330 CompletableFuture<?> b,
1331 Consumer<? super S> f, OrAccept<S> c) {
1332 Object r; Throwable x;
1333 if (a == null || b == null ||
1334 ((r = a.result) == null && (r = b.result) == null) || f == null)
1335 return false;
1336 if (result == null) {
1337 try {
1338 if (r instanceof AltResult) {
1339 x = ((AltResult)r).ex;
1340 r = null;
1341 }
1342 else
1343 x = null;
1344 if (x == null) {
1345 if (c != null && !c.claim())
1346 return false;
1347 else {
1348 @SuppressWarnings("unchecked") S t = (S) r;
1349 f.accept(t);
1350 }
1351 }
1352 } catch (Throwable ex) {
1353 x = ex;
1354 }
1355 internalComplete(encodeOutcome(null, x));
1356 }
1357 return true;
1358 }
1359
1360 private CompletableFuture<Void> orAcceptStage(
1361 Executor e, CompletionStage<? extends T> o, Consumer<? super T> f) {
1362 CompletableFuture<?> b;
1363 if (f == null || (b = o.toCompletableFuture()) == null)
1364 throw new NullPointerException();
1365 CompletableFuture<Void> d = new CompletableFuture<Void>();
1366 if (e != null || !d.orAccept(this, b, f, null)) {
1367 OrAccept<T> c = new OrAccept<T>(e, d, this, b, f);
1368 orpush(b, c);
1369 c.tryFire(SYNC);
1370 }
1371 return d;
1372 }
1373
1374 @SuppressWarnings("serial")
1375 static final class OrRun extends BiCompletion<Void> {
1376 Runnable fn;
1377 OrRun(Executor executor, CompletableFuture<Void> dep,
1378 CompletableFuture<?> src, CompletableFuture<?> snd, Runnable fn) {
1379 super(executor, dep, src, snd); this.fn = fn;
1380 }
1381 final CompletableFuture<?> tryFire(int mode) {
1382 CompletableFuture<Void> d; CompletableFuture<?> a, b;
1383 if ((d = dep) == null ||
1384 !d.orRun(a = src, b = snd, fn, mode > 0 ? null : this))
1385 return null;
1386 dep = null; snd = src = null; fn = null;
1387 return d.postFire(a, b, mode);
1388 }
1389 }
1390
1391 final boolean orRun(CompletableFuture<?> a, CompletableFuture<?> b,
1392 Runnable f, OrRun c) {
1393 Object r; Throwable x;
1394 if (a == null || b == null ||
1395 ((r = a.result) == null && (r = b.result) == null) || f == null)
1396 return false;
1397 if (result == null) {
1398 try {
1399 if (r instanceof AltResult)
1400 x = ((AltResult)r).ex;
1401 else
1402 x = null;
1403 if (x == null) {
1404 if (c != null && !c.claim())
1405 return false;
1406 else
1407 f.run();
1408 }
1409 } catch (Throwable ex) {
1410 x = ex;
1411 }
1412 internalComplete(encodeOutcome(null, x));
1413 }
1414 return true;
1415 }
1416
1417 private CompletableFuture<Void> orRunStage(Executor e, CompletionStage<?> o,
1418 Runnable f) {
1419 CompletableFuture<?> b;
1420 if (f == null || (b = o.toCompletableFuture()) == null)
1421 throw new NullPointerException();
1422 CompletableFuture<Void> d = new CompletableFuture<Void>();
1423 if (e != null || !d.orRun(this, b, f, null)) {
1424 OrRun c = new OrRun(e, d, this, b, f);
1425 orpush(b, c);
1426 c.tryFire(SYNC);
1427 }
1428 return d;
1429 }
1430
1431 @SuppressWarnings("serial")
1432 static final class OrRelay extends BiCompletion<Object> { // for Or
1433 OrRelay(CompletableFuture<Object> dep, CompletableFuture<?> src,
1434 CompletableFuture<?> snd) {
1435 super(null, dep, src, snd);
1436 }
1437 final CompletableFuture<?> tryFire(int mode) {
1438 CompletableFuture<Object> d; CompletableFuture<?> a, b;
1439 if ((d = dep) == null || !d.orRelay(a = src, b = snd))
1440 return null;
1441 snd = src = null; dep = null;
1442 return d.postFire(a, b, mode);
1443 }
1444 }
1445
1446 final boolean orRelay(CompletableFuture<?> a, CompletableFuture<?> b) {
1447 Object r;
1448 if (a == null || b == null ||
1449 ((r = a.result) == null && (r = b.result) == null))
1450 return false;
1451 Object s = encodeRelay(r);
1452 if (result == null)
1453 internalComplete(s);
1454 return true;
1455 }
1456
1457 /** Recursively constructs a tree of completions */
1458 static CompletableFuture<Object> orTree(CompletableFuture<?>[] cfs,
1459 int lo, int hi) {
1460 CompletableFuture<Object> d = new CompletableFuture<Object>();
1461 if (lo <= hi) {
1462 CompletableFuture<?> a, b;
1463 int mid = (lo + hi) >>> 1;
1464 if ((a = (lo == mid ? cfs[lo] :
1465 orTree(cfs, lo, mid))) == null ||
1466 (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
1467 orTree(cfs, mid+1, hi))) == null)
1468 throw new NullPointerException();
1469 if (!d.orRelay(a, b)) {
1470 OrRelay c = new OrRelay(d, a, b);
1471 a.orpush(b, c);
1472 c.tryFire(SYNC);
1473 }
1474 }
1475 return d;
1476 }
1477
1478 /* ------------- Zero-input Async forms -------------- */
1479
1480 @SuppressWarnings("serial")
1481 static final class AsyncSupply<T> extends Completion {
1482 CompletableFuture<T> dep; Supplier<T> fn;
1483 AsyncSupply(CompletableFuture<T> dep, Supplier<T> fn) {
1484 this.dep = dep; this.fn = fn;
1485 }
1486
1487 final CompletableFuture<?> tryFire(int alwaysAsync) {
1488 CompletableFuture<T> d; Supplier<T> f;
1489 if ((d = dep) != null && (f = fn) != null) {
1490 dep = null; fn = null;
1491 if (d.result == null) {
1492 T t; Throwable x;
1493 try {
1494 t = f.get();
1495 x = null;
1496 } catch (Throwable ex) {
1497 x = ex;
1498 t = null;
1499 }
1500 d.internalComplete(encodeOutcome(t, x));
1501 }
1502 d.postComplete();
1503 }
1504 return d;
1505 }
1506 final boolean isLive() { return dep != null; }
1507 }
1508
1509 static <U> CompletableFuture<U> asyncSupplyStage(Executor e,
1510 Supplier<U> f) {
1511 if (f == null) throw new NullPointerException();
1512 CompletableFuture<U> d = new CompletableFuture<U>();
1513 e.execute(new AsyncSupply<U>(d, f));
1514 return d;
1515 }
1516
1517 @SuppressWarnings("serial")
1518 static final class AsyncRun extends Completion {
1519 CompletableFuture<Void> dep; Runnable fn;
1520 AsyncRun(CompletableFuture<Void> dep, Runnable fn) {
1521 this.dep = dep; this.fn = fn;
1522 }
1523
1524 final CompletableFuture<?> tryFire(int alwaysAsync) {
1525 CompletableFuture<Void> d; Runnable f;
1526 if ((d = dep) != null && (f = fn) != null) {
1527 dep = null; fn = null;
1528 if (d.result == null) {
1529 Throwable x;
1530 try {
1531 f.run();
1532 x = null;
1533 } catch (Throwable ex) {
1534 x = ex;
1535 }
1536 d.internalComplete(encodeOutcome(null, x));
1537 }
1538 d.postComplete();
1539 }
1540 return d;
1541 }
1542 final boolean isLive() { return dep != null; }
1543 }
1544
1545 static CompletableFuture<Void> asyncRunStage(Executor e, Runnable f) {
1546 if (f == null) throw new NullPointerException();
1547 CompletableFuture<Void> d = new CompletableFuture<Void>();
1548 e.execute(new AsyncRun(d, f));
1549 return d;
1550 }
1551
1552 /* ------------- Signallers -------------- */
1553
1554 /**
1555 * Completion for recording and releasing a waiting thread. This
1556 * class implements ManagedBlocker to avoid starvation when
1557 * blocking actions pile up in ForkJoinPools.
1558 */
1559 @SuppressWarnings("serial")
1560 static final class Signaller extends Completion
1561 implements ForkJoinPool.ManagedBlocker {
1562 long nanos; // wait time if timed
1563 final long deadline; // non-zero if timed
1564 volatile int interruptControl; // > 0: interruptible, < 0: interrupted
1565 volatile Thread thread;
1566
1567 Signaller(boolean interruptible, long nanos, long deadline) {
1568 this.thread = Thread.currentThread();
1569 this.interruptControl = interruptible ? 1 : 0;
1570 this.nanos = nanos;
1571 this.deadline = deadline;
1572 }
1573 final CompletableFuture<?> tryFire(int ignore) {
1574 Thread w; // no need to atomically claim
1575 if ((w = thread) != null) {
1576 thread = null;
1577 LockSupport.unpark(w);
1578 }
1579 return null;
1580 }
1581 public boolean isReleasable() {
1582 if (thread == null)
1583 return true;
1584 if (Thread.interrupted()) {
1585 int i = interruptControl;
1586 interruptControl = -1;
1587 if (i > 0)
1588 return true;
1589 }
1590 if (deadline != 0L &&
1591 (nanos <= 0L || (nanos = deadline - System.nanoTime()) <= 0L)) {
1592 thread = null;
1593 return true;
1594 }
1595 return false;
1596 }
1597 public boolean block() {
1598 if (isReleasable())
1599 return true;
1600 else if (deadline == 0L)
1601 LockSupport.park(this);
1602 else if (nanos > 0L)
1603 LockSupport.parkNanos(this, nanos);
1604 return isReleasable();
1605 }
1606 final boolean isLive() { return thread != null; }
1607 }
1608
1609 /**
1610 * Returns raw result after waiting, or null if interruptible and
1611 * interrupted.
1612 */
1613 private Object waitingGet(boolean interruptible) {
1614 Signaller q = null;
1615 boolean queued = false;
1616 int spins = -1;
1617 Object r;
1618 while ((r = result) == null) {
1619 if (spins < 0)
1620 spins = (Runtime.getRuntime().availableProcessors() > 1) ?
1621 1 << 8 : 0; // Use brief spin-wait on multiprocessors
1622 else if (spins > 0) {
1623 if (ThreadLocalRandom.nextSecondarySeed() >= 0)
1624 --spins;
1625 }
1626 else if (q == null)
1627 q = new Signaller(interruptible, 0L, 0L);
1628 else if (!queued)
1629 queued = casStack(q.next = stack, q);
1630 else if (interruptible && q.interruptControl < 0) {
1631 q.thread = null;
1632 cleanStack();
1633 return null;
1634 }
1635 else if (q.thread != null && result == null) {
1636 try {
1637 ForkJoinPool.managedBlock(q);
1638 } catch (InterruptedException ie) {
1639 q.interruptControl = -1;
1640 }
1641 }
1642 }
1643 if (q != null) {
1644 q.thread = null;
1645 if (q.interruptControl < 0) {
1646 if (interruptible)
1647 r = null; // report interruption
1648 else
1649 Thread.currentThread().interrupt();
1650 }
1651 }
1652 postComplete();
1653 return r;
1654 }
1655
1656 /**
1657 * Returns raw result after waiting, or null if interrupted, or
1658 * throws TimeoutException on timeout.
1659 */
1660 private Object timedGet(long nanos) throws TimeoutException {
1661 if (Thread.interrupted())
1662 return null;
1663 if (nanos <= 0L)
1664 throw new TimeoutException();
1665 long d = System.nanoTime() + nanos;
1666 Signaller q = new Signaller(true, nanos, d == 0L ? 1L : d); // avoid 0
1667 boolean queued = false;
1668 Object r;
1669 while ((r = result) == null) {
1670 if (!queued)
1671 queued = casStack(q.next = stack, q);
1672 else if (q.interruptControl < 0 || q.nanos <= 0L) {
1673 q.thread = null;
1674 cleanStack();
1675 if (q.interruptControl < 0)
1676 return null;
1677 throw new TimeoutException();
1678 }
1679 else if (q.thread != null && result == null) {
1680 try {
1681 ForkJoinPool.managedBlock(q);
1682 } catch (InterruptedException ie) {
1683 q.interruptControl = -1;
1684 }
1685 }
1686 }
1687 if (q.interruptControl < 0)
1688 r = null;
1689 q.thread = null;
1690 postComplete();
1691 return r;
1692 }
1693
1694 /* ------------- public methods -------------- */
1695
1696 /**
1697 * Creates a new incomplete CompletableFuture.
1698 */
1699 public CompletableFuture() {
1700 }
1701
1702 /**
1703 * Returns a new CompletableFuture that is asynchronously completed
1704 * by a task running in the {@link ForkJoinPool#commonPool()} with
1705 * the value obtained by calling the given Supplier.
1706 *
1707 * @param supplier a function returning the value to be used
1708 * to complete the returned CompletableFuture
1709 * @param <U> the function's return type
1710 * @return the new CompletableFuture
1711 */
1712 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
1713 return asyncSupplyStage(asyncPool, supplier);
1714 }
1715
1716 /**
1717 * Returns a new CompletableFuture that is asynchronously completed
1718 * by a task running in the given executor with the value obtained
1719 * by calling the given Supplier.
1720 *
1721 * @param supplier a function returning the value to be used
1722 * to complete the returned CompletableFuture
1723 * @param executor the executor to use for asynchronous execution
1724 * @param <U> the function's return type
1725 * @return the new CompletableFuture
1726 */
1727 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
1728 Executor executor) {
1729 return asyncSupplyStage(screenExecutor(executor), supplier);
1730 }
1731
1732 /**
1733 * Returns a new CompletableFuture that is asynchronously completed
1734 * by a task running in the {@link ForkJoinPool#commonPool()} after
1735 * it runs the given action.
1736 *
1737 * @param runnable the action to run before completing the
1738 * returned CompletableFuture
1739 * @return the new CompletableFuture
1740 */
1741 public static CompletableFuture<Void> runAsync(Runnable runnable) {
1742 return asyncRunStage(asyncPool, runnable);
1743 }
1744
1745 /**
1746 * Returns a new CompletableFuture that is asynchronously completed
1747 * by a task running in the given executor after it runs the given
1748 * action.
1749 *
1750 * @param runnable the action to run before completing the
1751 * returned CompletableFuture
1752 * @param executor the executor to use for asynchronous execution
1753 * @return the new CompletableFuture
1754 */
1755 public static CompletableFuture<Void> runAsync(Runnable runnable,
1756 Executor executor) {
1757 return asyncRunStage(screenExecutor(executor), runnable);
1758 }
1759
1760 /**
1761 * Returns a new CompletableFuture that is already completed with
1762 * the given value.
1763 *
1764 * @param value the value
1765 * @param <U> the type of the value
1766 * @return the completed CompletableFuture
1767 */
1768 public static <U> CompletableFuture<U> completedFuture(U value) {
1769 CompletableFuture<U> d = new CompletableFuture<U>();
1770 d.result = (value == null) ? NIL : value;
1771 return d;
1772 }
1773
1774 /**
1775 * Returns {@code true} if completed in any fashion: normally,
1776 * exceptionally, or via cancellation.
1777 *
1778 * @return {@code true} if completed
1779 */
1780 public boolean isDone() {
1781 return result != null;
1782 }
1783
1784 /**
1785 * Waits if necessary for this future to complete, and then
1786 * returns its result.
1787 *
1788 * @return the result value
1789 * @throws CancellationException if this future was cancelled
1790 * @throws ExecutionException if this future completed exceptionally
1791 * @throws InterruptedException if the current thread was interrupted
1792 * while waiting
1793 */
1794 public T get() throws InterruptedException, ExecutionException {
1795 Object r;
1796 return reportGet((r = result) == null ? waitingGet(true) : r);
1797 }
1798
1799 /**
1800 * Waits if necessary for at most the given time for this future
1801 * to complete, and then returns its result, if available.
1802 *
1803 * @param timeout the maximum time to wait
1804 * @param unit the time unit of the timeout argument
1805 * @return the result value
1806 * @throws CancellationException if this future was cancelled
1807 * @throws ExecutionException if this future completed exceptionally
1808 * @throws InterruptedException if the current thread was interrupted
1809 * while waiting
1810 * @throws TimeoutException if the wait timed out
1811 */
1812 public T get(long timeout, TimeUnit unit)
1813 throws InterruptedException, ExecutionException, TimeoutException {
1814 Object r;
1815 long nanos = unit.toNanos(timeout);
1816 return reportGet((r = result) == null ? timedGet(nanos) : r);
1817 }
1818
1819 /**
1820 * Returns the result value when complete, or throws an
1821 * (unchecked) exception if completed exceptionally. To better
1822 * conform with the use of common functional forms, if a
1823 * computation involved in the completion of this
1824 * CompletableFuture threw an exception, this method throws an
1825 * (unchecked) {@link CompletionException} with the underlying
1826 * exception as its cause.
1827 *
1828 * @return the result value
1829 * @throws CancellationException if the computation was cancelled
1830 * @throws CompletionException if this future completed
1831 * exceptionally or a completion computation threw an exception
1832 */
1833 public T join() {
1834 Object r;
1835 return reportJoin((r = result) == null ? waitingGet(false) : r);
1836 }
1837
1838 /**
1839 * Returns the result value (or throws any encountered exception)
1840 * if completed, else returns the given valueIfAbsent.
1841 *
1842 * @param valueIfAbsent the value to return if not completed
1843 * @return the result value, if completed, else the given valueIfAbsent
1844 * @throws CancellationException if the computation was cancelled
1845 * @throws CompletionException if this future completed
1846 * exceptionally or a completion computation threw an exception
1847 */
1848 public T getNow(T valueIfAbsent) {
1849 Object r;
1850 return ((r = result) == null) ? valueIfAbsent : reportJoin(r);
1851 }
1852
1853 /**
1854 * If not already completed, sets the value returned by {@link
1855 * #get()} and related methods to the given value.
1856 *
1857 * @param value the result value
1858 * @return {@code true} if this invocation caused this CompletableFuture
1859 * to transition to a completed state, else {@code false}
1860 */
1861 public boolean complete(T value) {
1862 boolean triggered = internalComplete(value == null ? NIL : value);
1863 postComplete();
1864 return triggered;
1865 }
1866
1867 /**
1868 * If not already completed, causes invocations of {@link #get()}
1869 * and related methods to throw the given exception.
1870 *
1871 * @param ex the exception
1872 * @return {@code true} if this invocation caused this CompletableFuture
1873 * to transition to a completed state, else {@code false}
1874 */
1875 public boolean completeExceptionally(Throwable ex) {
1876 if (ex == null) throw new NullPointerException();
1877 boolean triggered = internalComplete(new AltResult(ex));
1878 postComplete();
1879 return triggered;
1880 }
1881
1882 public <U> CompletableFuture<U> thenApply(
1883 Function<? super T,? extends U> fn) {
1884 return uniApplyStage(null, fn);
1885 }
1886
1887 public <U> CompletableFuture<U> thenApplyAsync(
1888 Function<? super T,? extends U> fn) {
1889 return uniApplyStage(asyncPool, fn);
1890 }
1891
1892 public <U> CompletableFuture<U> thenApplyAsync(
1893 Function<? super T,? extends U> fn, Executor executor) {
1894 return uniApplyStage(screenExecutor(executor), fn);
1895 }
1896
1897 public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
1898 return uniAcceptStage(null, action);
1899 }
1900
1901 public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
1902 return uniAcceptStage(asyncPool, action);
1903 }
1904
1905 public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
1906 Executor executor) {
1907 return uniAcceptStage(screenExecutor(executor), action);
1908 }
1909
1910 public CompletableFuture<Void> thenRun(Runnable action) {
1911 return uniRunStage(null, action);
1912 }
1913
1914 public CompletableFuture<Void> thenRunAsync(Runnable action) {
1915 return uniRunStage(asyncPool, action);
1916 }
1917
1918 public CompletableFuture<Void> thenRunAsync(Runnable action,
1919 Executor executor) {
1920 return uniRunStage(screenExecutor(executor), action);
1921 }
1922
1923 public <U,V> CompletableFuture<V> thenCombine(
1924 CompletionStage<? extends U> other,
1925 BiFunction<? super T,? super U,? extends V> fn) {
1926 return biApplyStage(null, other, fn);
1927 }
1928
1929 public <U,V> CompletableFuture<V> thenCombineAsync(
1930 CompletionStage<? extends U> other,
1931 BiFunction<? super T,? super U,? extends V> fn) {
1932 return biApplyStage(asyncPool, other, fn);
1933 }
1934
1935 public <U,V> CompletableFuture<V> thenCombineAsync(
1936 CompletionStage<? extends U> other,
1937 BiFunction<? super T,? super U,? extends V> fn, Executor executor) {
1938 return biApplyStage(screenExecutor(executor), other, fn);
1939 }
1940
1941 public <U> CompletableFuture<Void> thenAcceptBoth(
1942 CompletionStage<? extends U> other,
1943 BiConsumer<? super T, ? super U> action) {
1944 return biAcceptStage(null, other, action);
1945 }
1946
1947 public <U> CompletableFuture<Void> thenAcceptBothAsync(
1948 CompletionStage<? extends U> other,
1949 BiConsumer<? super T, ? super U> action) {
1950 return biAcceptStage(asyncPool, other, action);
1951 }
1952
1953 public <U> CompletableFuture<Void> thenAcceptBothAsync(
1954 CompletionStage<? extends U> other,
1955 BiConsumer<? super T, ? super U> action, Executor executor) {
1956 return biAcceptStage(screenExecutor(executor), other, action);
1957 }
1958
1959 public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,
1960 Runnable action) {
1961 return biRunStage(null, other, action);
1962 }
1963
1964 public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
1965 Runnable action) {
1966 return biRunStage(asyncPool, other, action);
1967 }
1968
1969 public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
1970 Runnable action,
1971 Executor executor) {
1972 return biRunStage(screenExecutor(executor), other, action);
1973 }
1974
1975 public <U> CompletableFuture<U> applyToEither(
1976 CompletionStage<? extends T> other, Function<? super T, U> fn) {
1977 return orApplyStage(null, other, fn);
1978 }
1979
1980 public <U> CompletableFuture<U> applyToEitherAsync(
1981 CompletionStage<? extends T> other, Function<? super T, U> fn) {
1982 return orApplyStage(asyncPool, other, fn);
1983 }
1984
1985 public <U> CompletableFuture<U> applyToEitherAsync(
1986 CompletionStage<? extends T> other, Function<? super T, U> fn,
1987 Executor executor) {
1988 return orApplyStage(screenExecutor(executor), other, fn);
1989 }
1990
1991 public CompletableFuture<Void> acceptEither(
1992 CompletionStage<? extends T> other, Consumer<? super T> action) {
1993 return orAcceptStage(null, other, action);
1994 }
1995
1996 public CompletableFuture<Void> acceptEitherAsync(
1997 CompletionStage<? extends T> other, Consumer<? super T> action) {
1998 return orAcceptStage(asyncPool, other, action);
1999 }
2000
2001 public CompletableFuture<Void> acceptEitherAsync(
2002 CompletionStage<? extends T> other, Consumer<? super T> action,
2003 Executor executor) {
2004 return orAcceptStage(screenExecutor(executor), other, action);
2005 }
2006
2007 public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,
2008 Runnable action) {
2009 return orRunStage(null, other, action);
2010 }
2011
2012 public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
2013 Runnable action) {
2014 return orRunStage(asyncPool, other, action);
2015 }
2016
2017 public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
2018 Runnable action,
2019 Executor executor) {
2020 return orRunStage(screenExecutor(executor), other, action);
2021 }
2022
2023 public <U> CompletableFuture<U> thenCompose(
2024 Function<? super T, ? extends CompletionStage<U>> fn) {
2025 return uniComposeStage(null, fn);
2026 }
2027
2028 public <U> CompletableFuture<U> thenComposeAsync(
2029 Function<? super T, ? extends CompletionStage<U>> fn) {
2030 return uniComposeStage(asyncPool, fn);
2031 }
2032
2033 public <U> CompletableFuture<U> thenComposeAsync(
2034 Function<? super T, ? extends CompletionStage<U>> fn,
2035 Executor executor) {
2036 return uniComposeStage(screenExecutor(executor), fn);
2037 }
2038
2039 public CompletableFuture<T> whenComplete(
2040 BiConsumer<? super T, ? super Throwable> action) {
2041 return uniWhenCompleteStage(null, action);
2042 }
2043
2044 public CompletableFuture<T> whenCompleteAsync(
2045 BiConsumer<? super T, ? super Throwable> action) {
2046 return uniWhenCompleteStage(asyncPool, action);
2047 }
2048
2049 public CompletableFuture<T> whenCompleteAsync(
2050 BiConsumer<? super T, ? super Throwable> action, Executor executor) {
2051 return uniWhenCompleteStage(screenExecutor(executor), action);
2052 }
2053
2054 public <U> CompletableFuture<U> handle(
2055 BiFunction<? super T, Throwable, ? extends U> fn) {
2056 return uniHandleStage(null, fn);
2057 }
2058
2059 public <U> CompletableFuture<U> handleAsync(
2060 BiFunction<? super T, Throwable, ? extends U> fn) {
2061 return uniHandleStage(asyncPool, fn);
2062 }
2063
2064 public <U> CompletableFuture<U> handleAsync(
2065 BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) {
2066 return uniHandleStage(screenExecutor(executor), fn);
2067 }
2068
2069 /**
2070 * Returns this CompletableFuture.
2071 *
2072 * @return this CompletableFuture
2073 */
2074 public CompletableFuture<T> toCompletableFuture() {
2075 return this;
2076 }
2077
2078 // not in interface CompletionStage
2079
2080 /**
2081 * Returns a new CompletableFuture that is completed when this
2082 * CompletableFuture completes, with the result of the given
2083 * function of the exception triggering this CompletableFuture's
2084 * completion when it completes exceptionally; otherwise, if this
2085 * CompletableFuture completes normally, then the returned
2086 * CompletableFuture also completes normally with the same value.
2087 * Note: More flexible versions of this functionality are
2088 * available using methods {@code whenComplete} and {@code handle}.
2089 *
2090 * @param fn the function to use to compute the value of the
2091 * returned CompletableFuture if this CompletableFuture completed
2092 * exceptionally
2093 * @return the new CompletableFuture
2094 */
2095 public CompletableFuture<T> exceptionally(
2096 Function<Throwable, ? extends T> fn) {
2097 return uniExceptionallyStage(fn);
2098 }
2099
2100 /* ------------- Arbitrary-arity constructions -------------- */
2101
2102 /**
2103 * Returns a new CompletableFuture that is completed when all of
2104 * the given CompletableFutures complete. If any of the given
2105 * CompletableFutures complete exceptionally, then the returned
2106 * CompletableFuture also does so, with a CompletionException
2107 * holding this exception as its cause. Otherwise, the results,
2108 * if any, of the given CompletableFutures are not reflected in
2109 * the returned CompletableFuture, but may be obtained by
2110 * inspecting them individually. If no CompletableFutures are
2111 * provided, returns a CompletableFuture completed with the value
2112 * {@code null}.
2113 *
2114 * <p>Among the applications of this method is to await completion
2115 * of a set of independent CompletableFutures before continuing a
2116 * program, as in: {@code CompletableFuture.allOf(c1, c2,
2117 * c3).join();}.
2118 *
2119 * @param cfs the CompletableFutures
2120 * @return a new CompletableFuture that is completed when all of the
2121 * given CompletableFutures complete
2122 * @throws NullPointerException if the array or any of its elements are
2123 * {@code null}
2124 */
2125 public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
2126 return andTree(cfs, 0, cfs.length - 1);
2127 }
2128
2129 /**
2130 * Returns a new CompletableFuture that is completed when any of
2131 * the given CompletableFutures complete, with the same result.
2132 * Otherwise, if it completed exceptionally, the returned
2133 * CompletableFuture also does so, with a CompletionException
2134 * holding this exception as its cause. If no CompletableFutures
2135 * are provided, returns an incomplete CompletableFuture.
2136 *
2137 * @param cfs the CompletableFutures
2138 * @return a new CompletableFuture that is completed with the
2139 * result or exception of any of the given CompletableFutures when
2140 * one completes
2141 * @throws NullPointerException if the array or any of its elements are
2142 * {@code null}
2143 */
2144 public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
2145 return orTree(cfs, 0, cfs.length - 1);
2146 }
2147
2148 /* ------------- Control and status methods -------------- */
2149
2150 /**
2151 * If not already completed, completes this CompletableFuture with
2152 * a {@link CancellationException}. Dependent CompletableFutures
2153 * that have not already completed will also complete
2154 * exceptionally, with a {@link CompletionException} caused by
2155 * this {@code CancellationException}.
2156 *
2157 * @param mayInterruptIfRunning this value has no effect in this
2158 * implementation because interrupts are not used to control
2159 * processing.
2160 *
2161 * @return {@code true} if this task is now cancelled
2162 */
2163 public boolean cancel(boolean mayInterruptIfRunning) {
2164 boolean cancelled = (result == null) &&
2165 internalComplete(new AltResult(new CancellationException()));
2166 postComplete();
2167 return cancelled || isCancelled();
2168 }
2169
2170 /**
2171 * Returns {@code true} if this CompletableFuture was cancelled
2172 * before it completed normally.
2173 *
2174 * @return {@code true} if this CompletableFuture was cancelled
2175 * before it completed normally
2176 */
2177 public boolean isCancelled() {
2178 Object r;
2179 return ((r = result) instanceof AltResult) &&
2180 (((AltResult)r).ex instanceof CancellationException);
2181 }
2182
2183 /**
2184 * Returns {@code true} if this CompletableFuture completed
2185 * exceptionally, in any way. Possible causes include
2186 * cancellation, explicit invocation of {@code
2187 * completeExceptionally}, and abrupt termination of a
2188 * CompletionStage action.
2189 *
2190 * @return {@code true} if this CompletableFuture completed
2191 * exceptionally
2192 */
2193 public boolean isCompletedExceptionally() {
2194 Object r;
2195 return ((r = result) instanceof AltResult) && r != NIL;
2196 }
2197
2198 /**
2199 * Forcibly sets or resets the value subsequently returned by
2200 * method {@link #get()} and related methods, whether or not
2201 * already completed. This method is designed for use only in
2202 * error recovery actions, and even in such situations may result
2203 * in ongoing dependent completions using established versus
2204 * overwritten outcomes.
2205 *
2206 * @param value the completion value
2207 */
2208 public void obtrudeValue(T value) {
2209 result = (value == null) ? NIL : value;
2210 postComplete();
2211 }
2212
2213 /**
2214 * Forcibly causes subsequent invocations of method {@link #get()}
2215 * and related methods to throw the given exception, whether or
2216 * not already completed. This method is designed for use only in
2217 * recovery actions, and even in such situations may result in
2218 * ongoing dependent completions using established versus
2219 * overwritten outcomes.
2220 *
2221 * @param ex the exception
2222 */
2223 public void obtrudeException(Throwable ex) {
2224 if (ex == null) throw new NullPointerException();
2225 result = new AltResult(ex);
2226 postComplete();
2227 }
2228
2229 /**
2230 * Returns the estimated number of CompletableFutures whose
2231 * completions are awaiting completion of this CompletableFuture.
2232 * This method is designed for use in monitoring system state, not
2233 * for synchronization control.
2234 *
2235 * @return the number of dependent CompletableFutures
2236 */
2237 public int getNumberOfDependents() {
2238 int count = 0;
2239 for (Completion p = stack; p != null; p = p.next)
2240 ++count;
2241 return count;
2242 }
2243
2244 /**
2245 * Returns a string identifying this CompletableFuture, as well as
2246 * its completion state. The state, in brackets, contains the
2247 * String {@code "Completed Normally"} or the String {@code
2248 * "Completed Exceptionally"}, or the String {@code "Not
2249 * completed"} followed by the number of CompletableFutures
2250 * dependent upon its completion, if any.
2251 *
2252 * @return a string identifying this CompletableFuture, as well as its state
2253 */
2254 public String toString() {
2255 Object r = result;
2256 int count;
2257 return super.toString() +
2258 ((r == null) ?
2259 (((count = getNumberOfDependents()) == 0) ?
2260 "[Not completed]" :
2261 "[Not completed, " + count + " dependents]") :
2262 (((r instanceof AltResult) && ((AltResult)r).ex != null) ?
2263 "[Completed exceptionally]" :
2264 "[Completed normally]"));
2265 }
2266
2267 // Unsafe mechanics
2268 private static final sun.misc.Unsafe UNSAFE;
2269 private static final long RESULT;
2270 private static final long STACK;
2271 static {
2272 try {
2273 UNSAFE = sun.misc.Unsafe.getUnsafe();
2274 Class<?> k = CompletableFuture.class;
2275 RESULT = UNSAFE.objectFieldOffset
2276 (k.getDeclaredField("result"));
2277 STACK = UNSAFE.objectFieldOffset
2278 (k.getDeclaredField("stack"));
2279 } catch (Exception x) {
2280 throw new Error(x);
2281 }
2282 }
2283 }