ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.181
Committed: Sun Jan 24 22:41:31 2016 UTC (8 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.180: +7 -8 lines
Log Message:
delete stale comment "(see especially method Completion.detach)"

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