ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.175
Committed: Tue Sep 29 04:05:00 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.174: +2 -2 lines
Log Message:
javadoc clarity

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