ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.164
Committed: Sat Sep 5 15:07:18 2015 UTC (8 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.163: +12 -3 lines
Log Message:
Spec clarifications

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.</li>
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.</li>
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. </li>
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}. </li> </ul>
60 *
61 * <p>CompletableFuture also implements {@link Future} with the following
62 * policies: <ul>
63 *
64 * <li>Since (unlike {@link FutureTask}) this class has no direct
65 * control over the computation that causes it to be completed,
66 * cancellation is treated as just another form of exceptional
67 * completion. Method {@link #cancel cancel} has the same effect as
68 * {@code completeExceptionally(new CancellationException())}. Method
69 * {@link #isCompletedExceptionally} can be used to determine if a
70 * CompletableFuture completed in any exceptional fashion.</li>
71 *
72 * <li>In case of exceptional completion with a CompletionException,
73 * methods {@link #get()} and {@link #get(long, TimeUnit)} throw an
74 * {@link ExecutionException} with the same cause as held in the
75 * corresponding CompletionException. To simplify usage in most
76 * contexts, this class also defines methods {@link #join()} and
77 * {@link #getNow} that instead throw the CompletionException directly
78 * in these cases.</li> </ul>
79 *
80 * <p>Arguments used to pass a completion result (that is, for
81 * parameters of type {@code T}) for methods accepting them may be
82 * null, but passing a null value for any other parameter will result
83 * in a {@link NullPointerException} being thrown.
84 *
85 * <p>Subclasses of this class should normally override the "virtual
86 * constructor" method {@link #newIncompleteFuture}, which establishes
87 * the concrete type returned by CompletionStage methods. For example,
88 * here is a class that substitutes a different default Executor and
89 * disables the {@code obtrude} methods:
90 *
91 * <pre> {@code
92 * class MyCompletableFuture<T> extends CompletableFuture<T> {
93 * static final Executor myExecutor = ...;
94 * public MyCompletableFuture() { }
95 * public <U> CompletableFuture<U> newIncompleteFuture() {
96 * return new MyCompletableFuture<U>(); }
97 * public Executor defaultExecutor() {
98 * return myExecutor; }
99 * public void obtrudeValue(T value) {
100 * throw new UnsupportedOperationException(); }
101 * public void obtrudeException(Throwable ex) {
102 * throw new UnsupportedOperationException(); }
103 * }}</pre>
104 *
105 * @author Doug Lea
106 * @since 1.8
107 * @param <T> The result type returned by this future's {@code join}
108 * and {@code get} methods
109 */
110 public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {
111
112 /*
113 * Overview:
114 *
115 * A CompletableFuture may have dependent completion actions,
116 * collected in a linked stack. It atomically completes by CASing
117 * a result field, and then pops off and runs those actions. This
118 * applies across normal vs exceptional outcomes, sync vs async
119 * actions, binary triggers, and various forms of completions.
120 *
121 * Non-nullness of field result (set via CAS) indicates done. An
122 * AltResult is used to box null as a result, as well as to hold
123 * exceptions. Using a single field makes completion simple to
124 * detect and trigger. Encoding and decoding is straightforward
125 * but adds to the sprawl of trapping and associating exceptions
126 * with targets. Minor simplifications rely on (static) NIL (to
127 * box null results) being the only AltResult with a null
128 * exception field, so we don't usually need explicit comparisons.
129 * Even though some of the generics casts are unchecked (see
130 * SuppressWarnings annotations), they are placed to be
131 * appropriate even if checked.
132 *
133 * Dependent actions are represented by Completion objects linked
134 * as Treiber stacks headed by field "stack". There are Completion
135 * classes for each kind of action, grouped into single-input
136 * (UniCompletion), two-input (BiCompletion), projected
137 * (BiCompletions using either (not both) of two inputs), shared
138 * (CoCompletion, used by the second of two sources), zero-input
139 * source actions, and Signallers that unblock waiters. Class
140 * Completion extends ForkJoinTask to enable async execution
141 * (adding no space overhead because we exploit its "tag" methods
142 * to maintain claims). It is also declared as Runnable to allow
143 * usage with arbitrary executors.
144 *
145 * Support for each kind of CompletionStage relies on a separate
146 * class, along with two CompletableFuture methods:
147 *
148 * * A Completion class with name X corresponding to function,
149 * prefaced with "Uni", "Bi", or "Or". Each class contains
150 * fields for source(s), actions, and dependent. They are
151 * boringly similar, differing from others only with respect to
152 * underlying functional forms. We do this so that users don't
153 * encounter layers of adapters in common usages.
154 *
155 * * Boolean CompletableFuture method x(...) (for example
156 * uniApply) takes all of the arguments needed to check that an
157 * action is triggerable, and then either runs the action or
158 * arranges its async execution by executing its Completion
159 * argument, if present. The method returns true if known to be
160 * complete.
161 *
162 * * Completion method tryFire(int mode) invokes the associated x
163 * method with its held arguments, and on success cleans up.
164 * The mode argument allows tryFire to be called twice (SYNC,
165 * then ASYNC); the first to screen and trap exceptions while
166 * arranging to execute, and the second when called from a
167 * task. (A few classes are not used async so take slightly
168 * different forms.) The claim() callback suppresses function
169 * invocation if already claimed by another thread.
170 *
171 * * CompletableFuture method xStage(...) is called from a public
172 * stage method of CompletableFuture x. It screens user
173 * arguments and invokes and/or creates the stage object. If
174 * not async and x is already complete, the action is run
175 * immediately. Otherwise a Completion c is created, pushed to
176 * x's stack (unless done), and started or triggered via
177 * c.tryFire. This also covers races possible if x completes
178 * while pushing. Classes with two inputs (for example BiApply)
179 * deal with races across both while pushing actions. The
180 * second completion is a CoCompletion pointing to the first,
181 * shared so that at most one performs the action. The
182 * multiple-arity methods allOf and anyOf do this pairwise to
183 * form trees of completions.
184 *
185 * Note that the generic type parameters of methods vary according
186 * to whether "this" is a source, dependent, or completion.
187 *
188 * Method postComplete is called upon completion unless the target
189 * is guaranteed not to be observable (i.e., not yet returned or
190 * linked). Multiple threads can call postComplete, which
191 * atomically pops each dependent action, and tries to trigger it
192 * via method tryFire, in NESTED mode. Triggering can propagate
193 * recursively, so NESTED mode returns its completed dependent (if
194 * one exists) for further processing by its caller (see method
195 * postFire).
196 *
197 * Blocking methods get() and join() rely on Signaller Completions
198 * that wake up waiting threads. The mechanics are similar to
199 * Treiber stack wait-nodes used in FutureTask, Phaser, and
200 * SynchronousQueue. See their internal documentation for
201 * algorithmic details.
202 *
203 * Without precautions, CompletableFutures would be prone to
204 * garbage accumulation as chains of Completions build up, each
205 * pointing back to its sources. So we null out fields as soon as
206 * possible (see especially method Completion.detach). The
207 * screening checks needed anyway harmlessly ignore null arguments
208 * that may have been obtained during races with threads nulling
209 * out fields. We also try to unlink fired Completions from
210 * stacks that might never be popped (see method postFire).
211 * Completion fields need not be declared as final or volatile
212 * because they are only visible to other threads upon safe
213 * publication.
214 */
215
216 volatile Object result; // Either the result or boxed AltResult
217 volatile Completion stack; // Top of Treiber stack of dependent actions
218
219 final boolean internalComplete(Object r) { // CAS from null to r
220 return U.compareAndSwapObject(this, RESULT, null, r);
221 }
222
223 final boolean casStack(Completion cmp, Completion val) {
224 return U.compareAndSwapObject(this, STACK, cmp, val);
225 }
226
227 /** Returns true if successfully pushed c onto stack. */
228 final boolean tryPushStack(Completion c) {
229 Completion h = stack;
230 lazySetNext(c, h);
231 return U.compareAndSwapObject(this, STACK, h, c);
232 }
233
234 /** Unconditionally pushes c onto stack, retrying if necessary. */
235 final void pushStack(Completion c) {
236 do {} while (!tryPushStack(c));
237 }
238
239 /* ------------- Encoding and decoding outcomes -------------- */
240
241 static final class AltResult { // See above
242 final Throwable ex; // null only for NIL
243 AltResult(Throwable x) { this.ex = x; }
244 }
245
246 /** The encoding of the null value. */
247 static final AltResult NIL = new AltResult(null);
248
249 /** Completes with the null value, unless already completed. */
250 final boolean completeNull() {
251 return U.compareAndSwapObject(this, RESULT, null,
252 NIL);
253 }
254
255 /** Returns the encoding of the given non-exceptional value. */
256 final Object encodeValue(T t) {
257 return (t == null) ? NIL : t;
258 }
259
260 /** Completes with a non-exceptional result, unless already completed. */
261 final boolean completeValue(T t) {
262 return U.compareAndSwapObject(this, RESULT, null,
263 (t == null) ? NIL : t);
264 }
265
266 /**
267 * Returns the encoding of the given (non-null) exception as a
268 * wrapped CompletionException unless it is one already.
269 */
270 static AltResult encodeThrowable(Throwable x) {
271 return new AltResult((x instanceof CompletionException) ? x :
272 new CompletionException(x));
273 }
274
275 /** Completes with an exceptional result, unless already completed. */
276 final boolean completeThrowable(Throwable x) {
277 return U.compareAndSwapObject(this, RESULT, null,
278 encodeThrowable(x));
279 }
280
281 /**
282 * Returns the encoding of the given (non-null) exception as a
283 * wrapped CompletionException unless it is one already. May
284 * return the given Object r (which must have been the result of a
285 * source future) if it is equivalent, i.e. if this is a simple
286 * relay of an existing CompletionException.
287 */
288 static Object encodeThrowable(Throwable x, Object r) {
289 if (!(x instanceof CompletionException))
290 x = new CompletionException(x);
291 else if (r instanceof AltResult && x == ((AltResult)r).ex)
292 return r;
293 return new AltResult(x);
294 }
295
296 /**
297 * Completes with the given (non-null) exceptional result as a
298 * wrapped CompletionException unless it is one already, unless
299 * already completed. May complete with the given Object r
300 * (which must have been the result of a source future) if it is
301 * equivalent, i.e. if this is a simple propagation of an
302 * existing CompletionException.
303 */
304 final boolean completeThrowable(Throwable x, Object r) {
305 return U.compareAndSwapObject(this, RESULT, null,
306 encodeThrowable(x, r));
307 }
308
309 /**
310 * Returns the encoding of the given arguments: if the exception
311 * is non-null, encodes as AltResult. Otherwise uses the given
312 * value, boxed as NIL if null.
313 */
314 Object encodeOutcome(T t, Throwable x) {
315 return (x == null) ? (t == null) ? NIL : t : encodeThrowable(x);
316 }
317
318 /**
319 * Returns the encoding of a copied outcome; if exceptional,
320 * rewraps as a CompletionException, else returns argument.
321 */
322 static Object encodeRelay(Object r) {
323 Throwable x;
324 return (((r instanceof AltResult) &&
325 (x = ((AltResult)r).ex) != null &&
326 !(x instanceof CompletionException)) ?
327 new AltResult(new CompletionException(x)) : r);
328 }
329
330 /**
331 * Completes with r or a copy of r, unless already completed.
332 * If exceptional, r is first coerced to a CompletionException.
333 */
334 final boolean completeRelay(Object r) {
335 return U.compareAndSwapObject(this, RESULT, null,
336 encodeRelay(r));
337 }
338
339 /**
340 * Reports result using Future.get conventions.
341 */
342 private static <T> T reportGet(Object r)
343 throws InterruptedException, ExecutionException {
344 if (r == null) // by convention below, null means interrupted
345 throw new InterruptedException();
346 if (r instanceof AltResult) {
347 Throwable x, cause;
348 if ((x = ((AltResult)r).ex) == null)
349 return null;
350 if (x instanceof CancellationException)
351 throw (CancellationException)x;
352 if ((x instanceof CompletionException) &&
353 (cause = x.getCause()) != null)
354 x = cause;
355 throw new ExecutionException(x);
356 }
357 @SuppressWarnings("unchecked") T t = (T) r;
358 return t;
359 }
360
361 /**
362 * Decodes outcome to return result or throw unchecked exception.
363 */
364 private static <T> T reportJoin(Object r) {
365 if (r instanceof AltResult) {
366 Throwable x;
367 if ((x = ((AltResult)r).ex) == null)
368 return null;
369 if (x instanceof CancellationException)
370 throw (CancellationException)x;
371 if (x instanceof CompletionException)
372 throw (CompletionException)x;
373 throw new CompletionException(x);
374 }
375 @SuppressWarnings("unchecked") T t = (T) r;
376 return t;
377 }
378
379 /* ------------- Async task preliminaries -------------- */
380
381 /**
382 * A marker interface identifying asynchronous tasks produced by
383 * {@code async} methods. This may be useful for monitoring,
384 * debugging, and tracking asynchronous activities.
385 *
386 * @since 1.8
387 */
388 public static interface AsynchronousCompletionTask {
389 }
390
391 private static final boolean useCommonPool =
392 (ForkJoinPool.getCommonPoolParallelism() > 1);
393
394 /**
395 * Default executor -- ForkJoinPool.commonPool() unless it cannot
396 * support parallelism.
397 */
398 private static final Executor asyncPool = useCommonPool ?
399 ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
400
401 /** Fallback if ForkJoinPool.commonPool() cannot support parallelism */
402 static final class ThreadPerTaskExecutor implements Executor {
403 public void execute(Runnable r) { new Thread(r).start(); }
404 }
405
406 /**
407 * Null-checks user executor argument, and translates uses of
408 * commonPool to asyncPool in case parallelism disabled.
409 */
410 static Executor screenExecutor(Executor e) {
411 if (!useCommonPool && e == ForkJoinPool.commonPool())
412 return asyncPool;
413 if (e == null) throw new NullPointerException();
414 return e;
415 }
416
417 // Modes for Completion.tryFire. Signedness matters.
418 static final int SYNC = 0;
419 static final int ASYNC = 1;
420 static final int NESTED = -1;
421
422 /* ------------- Base Completion classes and operations -------------- */
423
424 @SuppressWarnings("serial")
425 abstract static class Completion extends ForkJoinTask<Void>
426 implements Runnable, AsynchronousCompletionTask {
427 volatile Completion next; // Treiber stack link
428
429 /**
430 * Performs completion action if triggered, returning a
431 * dependent that may need propagation, if one exists.
432 *
433 * @param mode SYNC, ASYNC, or NESTED
434 */
435 abstract CompletableFuture<?> tryFire(int mode);
436
437 /** Returns true if possibly still triggerable. Used by cleanStack. */
438 abstract boolean isLive();
439
440 public final void run() { tryFire(ASYNC); }
441 public final boolean exec() { tryFire(ASYNC); return false; }
442 public final Void getRawResult() { return null; }
443 public final void setRawResult(Void v) {}
444 }
445
446 static void lazySetNext(Completion c, Completion next) {
447 U.putOrderedObject(c, NEXT, next);
448 }
449
450 /**
451 * Pops and tries to trigger all reachable dependents. Call only
452 * when known to be done.
453 */
454 final void postComplete() {
455 /*
456 * On each step, variable f holds current dependents to pop
457 * and run. It is extended along only one path at a time,
458 * pushing others to avoid unbounded recursion.
459 */
460 CompletableFuture<?> f = this; Completion h;
461 while ((h = f.stack) != null ||
462 (f != this && (h = (f = this).stack) != null)) {
463 CompletableFuture<?> d; Completion t;
464 if (f.casStack(h, t = h.next)) {
465 if (t != null) {
466 if (f != this) {
467 pushStack(h);
468 continue;
469 }
470 h.next = null; // detach
471 }
472 f = (d = h.tryFire(NESTED)) == null ? this : d;
473 }
474 }
475 }
476
477 /** Traverses stack and unlinks dead Completions. */
478 final void cleanStack() {
479 for (Completion p = null, q = stack; q != null;) {
480 Completion s = q.next;
481 if (q.isLive()) {
482 p = q;
483 q = s;
484 }
485 else if (p == null) {
486 casStack(q, s);
487 q = stack;
488 }
489 else {
490 p.next = s;
491 if (p.isLive())
492 q = s;
493 else {
494 p = null; // restart
495 q = stack;
496 }
497 }
498 }
499 }
500
501 /* ------------- One-input Completions -------------- */
502
503 /** A Completion with a source, dependent, and executor. */
504 @SuppressWarnings("serial")
505 abstract static class UniCompletion<T,V> extends Completion {
506 Executor executor; // executor to use (null if none)
507 CompletableFuture<V> dep; // the dependent to complete
508 CompletableFuture<T> src; // source for action
509
510 UniCompletion(Executor executor, CompletableFuture<V> dep,
511 CompletableFuture<T> src) {
512 this.executor = executor; this.dep = dep; this.src = src;
513 }
514
515 /**
516 * Returns true if action can be run. Call only when known to
517 * be triggerable. Uses FJ tag bit to ensure that only one
518 * thread claims ownership. If async, starts as task -- a
519 * later call to tryFire will run action.
520 */
521 final boolean claim() {
522 Executor e = executor;
523 if (compareAndSetForkJoinTaskTag((short)0, (short)1)) {
524 if (e == null)
525 return true;
526 executor = null; // disable
527 e.execute(this);
528 }
529 return false;
530 }
531
532 final boolean isLive() { return dep != null; }
533 }
534
535 /** Pushes the given completion (if it exists) unless done. */
536 final void push(UniCompletion<?,?> c) {
537 if (c != null) {
538 while (result == null && !tryPushStack(c))
539 lazySetNext(c, null); // clear on failure
540 }
541 }
542
543 /**
544 * Post-processing by dependent after successful UniCompletion
545 * tryFire. Tries to clean stack of source a, and then either runs
546 * postComplete or returns this to caller, depending on mode.
547 */
548 final CompletableFuture<T> postFire(CompletableFuture<?> a, int mode) {
549 if (a != null && a.stack != null) {
550 if (mode < 0 || a.result == null)
551 a.cleanStack();
552 else
553 a.postComplete();
554 }
555 if (result != null && stack != null) {
556 if (mode < 0)
557 return this;
558 else
559 postComplete();
560 }
561 return null;
562 }
563
564 @SuppressWarnings("serial")
565 static final class UniApply<T,V> extends UniCompletion<T,V> {
566 Function<? super T,? extends V> fn;
567 UniApply(Executor executor, CompletableFuture<V> dep,
568 CompletableFuture<T> src,
569 Function<? super T,? extends V> fn) {
570 super(executor, dep, src); this.fn = fn;
571 }
572 final CompletableFuture<V> tryFire(int mode) {
573 CompletableFuture<V> d; CompletableFuture<T> a;
574 if ((d = dep) == null ||
575 !d.uniApply(a = src, fn, mode > 0 ? null : this))
576 return null;
577 dep = null; src = null; fn = null;
578 return d.postFire(a, mode);
579 }
580 }
581
582 final <S> boolean uniApply(CompletableFuture<S> a,
583 Function<? super S,? extends T> f,
584 UniApply<S,T> c) {
585 Object r; Throwable x;
586 if (a == null || (r = a.result) == null || f == null)
587 return false;
588 tryComplete: if (result == null) {
589 if (r instanceof AltResult) {
590 if ((x = ((AltResult)r).ex) != null) {
591 completeThrowable(x, r);
592 break tryComplete;
593 }
594 r = null;
595 }
596 try {
597 if (c != null && !c.claim())
598 return false;
599 @SuppressWarnings("unchecked") S s = (S) r;
600 completeValue(f.apply(s));
601 } catch (Throwable ex) {
602 completeThrowable(ex);
603 }
604 }
605 return true;
606 }
607
608 private <V> CompletableFuture<V> uniApplyStage(
609 Executor e, Function<? super T,? extends V> f) {
610 if (f == null) throw new NullPointerException();
611 CompletableFuture<V> d = newIncompleteFuture();
612 if (e != null || !d.uniApply(this, f, null)) {
613 UniApply<T,V> c = new UniApply<T,V>(e, d, this, f);
614 push(c);
615 c.tryFire(SYNC);
616 }
617 return d;
618 }
619
620 @SuppressWarnings("serial")
621 static final class UniAccept<T> extends UniCompletion<T,Void> {
622 Consumer<? super T> fn;
623 UniAccept(Executor executor, CompletableFuture<Void> dep,
624 CompletableFuture<T> src, Consumer<? super T> fn) {
625 super(executor, dep, src); this.fn = fn;
626 }
627 final CompletableFuture<Void> tryFire(int mode) {
628 CompletableFuture<Void> d; CompletableFuture<T> a;
629 if ((d = dep) == null ||
630 !d.uniAccept(a = src, fn, mode > 0 ? null : this))
631 return null;
632 dep = null; src = null; fn = null;
633 return d.postFire(a, mode);
634 }
635 }
636
637 final <S> boolean uniAccept(CompletableFuture<S> a,
638 Consumer<? super S> f, UniAccept<S> c) {
639 Object r; Throwable x;
640 if (a == null || (r = a.result) == null || f == null)
641 return false;
642 tryComplete: if (result == null) {
643 if (r instanceof AltResult) {
644 if ((x = ((AltResult)r).ex) != null) {
645 completeThrowable(x, r);
646 break tryComplete;
647 }
648 r = null;
649 }
650 try {
651 if (c != null && !c.claim())
652 return false;
653 @SuppressWarnings("unchecked") S s = (S) r;
654 f.accept(s);
655 completeNull();
656 } catch (Throwable ex) {
657 completeThrowable(ex);
658 }
659 }
660 return true;
661 }
662
663 private CompletableFuture<Void> uniAcceptStage(Executor e,
664 Consumer<? super T> f) {
665 if (f == null) throw new NullPointerException();
666 CompletableFuture<Void> d = newIncompleteFuture();
667 if (e != null || !d.uniAccept(this, f, null)) {
668 UniAccept<T> c = new UniAccept<T>(e, d, this, f);
669 push(c);
670 c.tryFire(SYNC);
671 }
672 return d;
673 }
674
675 @SuppressWarnings("serial")
676 static final class UniRun<T> extends UniCompletion<T,Void> {
677 Runnable fn;
678 UniRun(Executor executor, CompletableFuture<Void> dep,
679 CompletableFuture<T> src, Runnable fn) {
680 super(executor, dep, src); this.fn = fn;
681 }
682 final CompletableFuture<Void> tryFire(int mode) {
683 CompletableFuture<Void> d; CompletableFuture<T> a;
684 if ((d = dep) == null ||
685 !d.uniRun(a = src, fn, mode > 0 ? null : this))
686 return null;
687 dep = null; src = null; fn = null;
688 return d.postFire(a, mode);
689 }
690 }
691
692 final boolean uniRun(CompletableFuture<?> a, Runnable f, UniRun<?> c) {
693 Object r; Throwable x;
694 if (a == null || (r = a.result) == null || f == null)
695 return false;
696 if (result == null) {
697 if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
698 completeThrowable(x, r);
699 else
700 try {
701 if (c != null && !c.claim())
702 return false;
703 f.run();
704 completeNull();
705 } catch (Throwable ex) {
706 completeThrowable(ex);
707 }
708 }
709 return true;
710 }
711
712 private CompletableFuture<Void> uniRunStage(Executor e, Runnable f) {
713 if (f == null) throw new NullPointerException();
714 CompletableFuture<Void> d = newIncompleteFuture();
715 if (e != null || !d.uniRun(this, f, null)) {
716 UniRun<T> c = new UniRun<T>(e, d, this, f);
717 push(c);
718 c.tryFire(SYNC);
719 }
720 return d;
721 }
722
723 @SuppressWarnings("serial")
724 static final class UniWhenComplete<T> extends UniCompletion<T,T> {
725 BiConsumer<? super T, ? super Throwable> fn;
726 UniWhenComplete(Executor executor, CompletableFuture<T> dep,
727 CompletableFuture<T> src,
728 BiConsumer<? super T, ? super Throwable> fn) {
729 super(executor, dep, src); this.fn = fn;
730 }
731 final CompletableFuture<T> tryFire(int mode) {
732 CompletableFuture<T> d; CompletableFuture<T> a;
733 if ((d = dep) == null ||
734 !d.uniWhenComplete(a = src, fn, mode > 0 ? null : this))
735 return null;
736 dep = null; src = null; fn = null;
737 return d.postFire(a, mode);
738 }
739 }
740
741 final boolean uniWhenComplete(CompletableFuture<T> a,
742 BiConsumer<? super T,? super Throwable> f,
743 UniWhenComplete<T> c) {
744 Object r; T t; Throwable x = null;
745 if (a == null || (r = a.result) == null || f == null)
746 return false;
747 if (result == null) {
748 try {
749 if (c != null && !c.claim())
750 return false;
751 if (r instanceof AltResult) {
752 x = ((AltResult)r).ex;
753 t = null;
754 } else {
755 @SuppressWarnings("unchecked") T tr = (T) r;
756 t = tr;
757 }
758 f.accept(t, x);
759 if (x == null) {
760 internalComplete(r);
761 return true;
762 }
763 } catch (Throwable ex) {
764 if (x == null)
765 x = ex;
766 }
767 completeThrowable(x, r);
768 }
769 return true;
770 }
771
772 private CompletableFuture<T> uniWhenCompleteStage(
773 Executor e, BiConsumer<? super T, ? super Throwable> f) {
774 if (f == null) throw new NullPointerException();
775 CompletableFuture<T> d = newIncompleteFuture();
776 if (e != null || !d.uniWhenComplete(this, f, null)) {
777 UniWhenComplete<T> c = new UniWhenComplete<T>(e, d, this, f);
778 push(c);
779 c.tryFire(SYNC);
780 }
781 return d;
782 }
783
784 @SuppressWarnings("serial")
785 static final class UniHandle<T,V> extends UniCompletion<T,V> {
786 BiFunction<? super T, Throwable, ? extends V> fn;
787 UniHandle(Executor executor, CompletableFuture<V> dep,
788 CompletableFuture<T> src,
789 BiFunction<? super T, Throwable, ? extends V> fn) {
790 super(executor, dep, src); this.fn = fn;
791 }
792 final CompletableFuture<V> tryFire(int mode) {
793 CompletableFuture<V> d; CompletableFuture<T> a;
794 if ((d = dep) == null ||
795 !d.uniHandle(a = src, fn, mode > 0 ? null : this))
796 return null;
797 dep = null; src = null; fn = null;
798 return d.postFire(a, mode);
799 }
800 }
801
802 final <S> boolean uniHandle(CompletableFuture<S> a,
803 BiFunction<? super S, Throwable, ? extends T> f,
804 UniHandle<S,T> c) {
805 Object r; S s; Throwable x;
806 if (a == null || (r = a.result) == null || f == null)
807 return false;
808 if (result == null) {
809 try {
810 if (c != null && !c.claim())
811 return false;
812 if (r instanceof AltResult) {
813 x = ((AltResult)r).ex;
814 s = null;
815 } else {
816 x = null;
817 @SuppressWarnings("unchecked") S ss = (S) r;
818 s = ss;
819 }
820 completeValue(f.apply(s, x));
821 } catch (Throwable ex) {
822 completeThrowable(ex);
823 }
824 }
825 return true;
826 }
827
828 private <V> CompletableFuture<V> uniHandleStage(
829 Executor e, BiFunction<? super T, Throwable, ? extends V> f) {
830 if (f == null) throw new NullPointerException();
831 CompletableFuture<V> d = newIncompleteFuture();
832 if (e != null || !d.uniHandle(this, f, null)) {
833 UniHandle<T,V> c = new UniHandle<T,V>(e, d, this, f);
834 push(c);
835 c.tryFire(SYNC);
836 }
837 return d;
838 }
839
840 @SuppressWarnings("serial")
841 static final class UniExceptionally<T> extends UniCompletion<T,T> {
842 Function<? super Throwable, ? extends T> fn;
843 UniExceptionally(CompletableFuture<T> dep, CompletableFuture<T> src,
844 Function<? super Throwable, ? extends T> fn) {
845 super(null, dep, src); this.fn = fn;
846 }
847 final CompletableFuture<T> tryFire(int mode) { // never ASYNC
848 // assert mode != ASYNC;
849 CompletableFuture<T> d; CompletableFuture<T> a;
850 if ((d = dep) == null || !d.uniExceptionally(a = src, fn, this))
851 return null;
852 dep = null; src = null; fn = null;
853 return d.postFire(a, mode);
854 }
855 }
856
857 final boolean uniExceptionally(CompletableFuture<T> a,
858 Function<? super Throwable, ? extends T> f,
859 UniExceptionally<T> c) {
860 Object r; Throwable x;
861 if (a == null || (r = a.result) == null || f == null)
862 return false;
863 if (result == null) {
864 try {
865 if (r instanceof AltResult && (x = ((AltResult)r).ex) != null) {
866 if (c != null && !c.claim())
867 return false;
868 completeValue(f.apply(x));
869 } else
870 internalComplete(r);
871 } catch (Throwable ex) {
872 completeThrowable(ex);
873 }
874 }
875 return true;
876 }
877
878 private CompletableFuture<T> uniExceptionallyStage(
879 Function<Throwable, ? extends T> f) {
880 if (f == null) throw new NullPointerException();
881 CompletableFuture<T> d = newIncompleteFuture();
882 if (!d.uniExceptionally(this, f, null)) {
883 UniExceptionally<T> c = new UniExceptionally<T>(d, this, f);
884 push(c);
885 c.tryFire(SYNC);
886 }
887 return d;
888 }
889
890 @SuppressWarnings("serial")
891 static final class UniRelay<T> extends UniCompletion<T,T> { // for Compose
892 UniRelay(CompletableFuture<T> dep, CompletableFuture<T> src) {
893 super(null, dep, src);
894 }
895 final CompletableFuture<T> tryFire(int mode) {
896 CompletableFuture<T> d; CompletableFuture<T> a;
897 if ((d = dep) == null || !d.uniRelay(a = src))
898 return null;
899 src = null; dep = null;
900 return d.postFire(a, mode);
901 }
902 }
903
904 final boolean uniRelay(CompletableFuture<T> a) {
905 Object r;
906 if (a == null || (r = a.result) == null)
907 return false;
908 if (result == null) // no need to claim
909 completeRelay(r);
910 return true;
911 }
912
913 private CompletableFuture<T> uniCopyStage() {
914 Object r;
915 CompletableFuture<T> d = newIncompleteFuture();
916 if ((r = result) != null)
917 d.completeRelay(r);
918 else {
919 UniRelay<T> c = new UniRelay<T>(d, this);
920 push(c);
921 c.tryFire(SYNC);
922 }
923 return d;
924 }
925
926 private MinimalStage<T> uniAsMinimalStage() {
927 Object r;
928 if ((r = result) != null)
929 return new MinimalStage<T>(encodeRelay(r));
930 MinimalStage<T> d = new MinimalStage<T>();
931 UniRelay<T> c = new UniRelay<T>(d, this);
932 push(c);
933 c.tryFire(SYNC);
934 return d;
935 }
936
937 @SuppressWarnings("serial")
938 static final class UniCompose<T,V> extends UniCompletion<T,V> {
939 Function<? super T, ? extends CompletionStage<V>> fn;
940 UniCompose(Executor executor, CompletableFuture<V> dep,
941 CompletableFuture<T> src,
942 Function<? super T, ? extends CompletionStage<V>> fn) {
943 super(executor, dep, src); this.fn = fn;
944 }
945 final CompletableFuture<V> tryFire(int mode) {
946 CompletableFuture<V> d; CompletableFuture<T> a;
947 if ((d = dep) == null ||
948 !d.uniCompose(a = src, fn, mode > 0 ? null : this))
949 return null;
950 dep = null; src = null; fn = null;
951 return d.postFire(a, mode);
952 }
953 }
954
955 final <S> boolean uniCompose(
956 CompletableFuture<S> a,
957 Function<? super S, ? extends CompletionStage<T>> f,
958 UniCompose<S,T> c) {
959 Object r; Throwable x;
960 if (a == null || (r = a.result) == null || f == null)
961 return false;
962 tryComplete: if (result == null) {
963 if (r instanceof AltResult) {
964 if ((x = ((AltResult)r).ex) != null) {
965 completeThrowable(x, r);
966 break tryComplete;
967 }
968 r = null;
969 }
970 try {
971 if (c != null && !c.claim())
972 return false;
973 @SuppressWarnings("unchecked") S s = (S) r;
974 CompletableFuture<T> g = f.apply(s).toCompletableFuture();
975 if (g.result == null || !uniRelay(g)) {
976 UniRelay<T> copy = new UniRelay<T>(this, g);
977 g.push(copy);
978 copy.tryFire(SYNC);
979 if (result == null)
980 return false;
981 }
982 } catch (Throwable ex) {
983 completeThrowable(ex);
984 }
985 }
986 return true;
987 }
988
989 private <V> CompletableFuture<V> uniComposeStage(
990 Executor e, Function<? super T, ? extends CompletionStage<V>> f) {
991 if (f == null) throw new NullPointerException();
992 Object r, s; Throwable x;
993 CompletableFuture<V> d = newIncompleteFuture();
994 if (e == null && (r = result) != null) {
995 if (r instanceof AltResult) {
996 if ((x = ((AltResult)r).ex) != null) {
997 d.result = encodeThrowable(x, r);
998 return d;
999 }
1000 r = null;
1001 }
1002 try {
1003 @SuppressWarnings("unchecked") T t = (T) r;
1004 CompletableFuture<V> g = f.apply(t).toCompletableFuture();
1005 if ((s = g.result) != null)
1006 d.completeRelay(s);
1007 else {
1008 UniRelay<V> c = new UniRelay<V>(d, g);
1009 g.push(c);
1010 c.tryFire(SYNC);
1011 }
1012 return d;
1013 } catch (Throwable ex) {
1014 d.result = encodeThrowable(ex);
1015 return d;
1016 }
1017 }
1018 UniCompose<T,V> c = new UniCompose<T,V>(e, d, this, f);
1019 push(c);
1020 c.tryFire(SYNC);
1021 return d;
1022 }
1023
1024 /* ------------- Two-input Completions -------------- */
1025
1026 /** A Completion for an action with two sources */
1027 @SuppressWarnings("serial")
1028 abstract static class BiCompletion<T,U,V> extends UniCompletion<T,V> {
1029 CompletableFuture<U> snd; // second source for action
1030 BiCompletion(Executor executor, CompletableFuture<V> dep,
1031 CompletableFuture<T> src, CompletableFuture<U> snd) {
1032 super(executor, dep, src); this.snd = snd;
1033 }
1034 }
1035
1036 /** A Completion delegating to a BiCompletion */
1037 @SuppressWarnings("serial")
1038 static final class CoCompletion extends Completion {
1039 BiCompletion<?,?,?> base;
1040 CoCompletion(BiCompletion<?,?,?> base) { this.base = base; }
1041 final CompletableFuture<?> tryFire(int mode) {
1042 BiCompletion<?,?,?> c; CompletableFuture<?> d;
1043 if ((c = base) == null || (d = c.tryFire(mode)) == null)
1044 return null;
1045 base = null; // detach
1046 return d;
1047 }
1048 final boolean isLive() {
1049 BiCompletion<?,?,?> c;
1050 return (c = base) != null && c.dep != null;
1051 }
1052 }
1053
1054 /** Pushes completion to this and b unless both done. */
1055 final void bipush(CompletableFuture<?> b, BiCompletion<?,?,?> c) {
1056 if (c != null) {
1057 Object r;
1058 while ((r = result) == null && !tryPushStack(c))
1059 lazySetNext(c, null); // clear on failure
1060 if (b != null && b != this && b.result == null) {
1061 Completion q = (r != null) ? c : new CoCompletion(c);
1062 while (b.result == null && !b.tryPushStack(q))
1063 lazySetNext(q, null); // clear on failure
1064 }
1065 }
1066 }
1067
1068 /** Post-processing after successful BiCompletion tryFire. */
1069 final CompletableFuture<T> postFire(CompletableFuture<?> a,
1070 CompletableFuture<?> b, int mode) {
1071 if (b != null && b.stack != null) { // clean second source
1072 if (mode < 0 || b.result == null)
1073 b.cleanStack();
1074 else
1075 b.postComplete();
1076 }
1077 return postFire(a, mode);
1078 }
1079
1080 @SuppressWarnings("serial")
1081 static final class BiApply<T,U,V> extends BiCompletion<T,U,V> {
1082 BiFunction<? super T,? super U,? extends V> fn;
1083 BiApply(Executor executor, CompletableFuture<V> dep,
1084 CompletableFuture<T> src, CompletableFuture<U> snd,
1085 BiFunction<? super T,? super U,? extends V> fn) {
1086 super(executor, dep, src, snd); this.fn = fn;
1087 }
1088 final CompletableFuture<V> tryFire(int mode) {
1089 CompletableFuture<V> d;
1090 CompletableFuture<T> a;
1091 CompletableFuture<U> b;
1092 if ((d = dep) == null ||
1093 !d.biApply(a = src, b = snd, fn, mode > 0 ? null : this))
1094 return null;
1095 dep = null; src = null; snd = null; fn = null;
1096 return d.postFire(a, b, mode);
1097 }
1098 }
1099
1100 final <R,S> boolean biApply(CompletableFuture<R> a,
1101 CompletableFuture<S> b,
1102 BiFunction<? super R,? super S,? extends T> f,
1103 BiApply<R,S,T> c) {
1104 Object r, s; Throwable x;
1105 if (a == null || (r = a.result) == null ||
1106 b == null || (s = b.result) == null || f == null)
1107 return false;
1108 tryComplete: if (result == null) {
1109 if (r instanceof AltResult) {
1110 if ((x = ((AltResult)r).ex) != null) {
1111 completeThrowable(x, r);
1112 break tryComplete;
1113 }
1114 r = null;
1115 }
1116 if (s instanceof AltResult) {
1117 if ((x = ((AltResult)s).ex) != null) {
1118 completeThrowable(x, s);
1119 break tryComplete;
1120 }
1121 s = null;
1122 }
1123 try {
1124 if (c != null && !c.claim())
1125 return false;
1126 @SuppressWarnings("unchecked") R rr = (R) r;
1127 @SuppressWarnings("unchecked") S ss = (S) s;
1128 completeValue(f.apply(rr, ss));
1129 } catch (Throwable ex) {
1130 completeThrowable(ex);
1131 }
1132 }
1133 return true;
1134 }
1135
1136 private <U,V> CompletableFuture<V> biApplyStage(
1137 Executor e, CompletionStage<U> o,
1138 BiFunction<? super T,? super U,? extends V> f) {
1139 CompletableFuture<U> b;
1140 if (f == null || (b = o.toCompletableFuture()) == null)
1141 throw new NullPointerException();
1142 CompletableFuture<V> d = newIncompleteFuture();
1143 if (e != null || !d.biApply(this, b, f, null)) {
1144 BiApply<T,U,V> c = new BiApply<T,U,V>(e, d, this, b, f);
1145 bipush(b, c);
1146 c.tryFire(SYNC);
1147 }
1148 return d;
1149 }
1150
1151 @SuppressWarnings("serial")
1152 static final class BiAccept<T,U> extends BiCompletion<T,U,Void> {
1153 BiConsumer<? super T,? super U> fn;
1154 BiAccept(Executor executor, CompletableFuture<Void> dep,
1155 CompletableFuture<T> src, CompletableFuture<U> snd,
1156 BiConsumer<? super T,? super U> fn) {
1157 super(executor, dep, src, snd); this.fn = fn;
1158 }
1159 final CompletableFuture<Void> tryFire(int mode) {
1160 CompletableFuture<Void> d;
1161 CompletableFuture<T> a;
1162 CompletableFuture<U> b;
1163 if ((d = dep) == null ||
1164 !d.biAccept(a = src, b = snd, fn, mode > 0 ? null : this))
1165 return null;
1166 dep = null; src = null; snd = null; fn = null;
1167 return d.postFire(a, b, mode);
1168 }
1169 }
1170
1171 final <R,S> boolean biAccept(CompletableFuture<R> a,
1172 CompletableFuture<S> b,
1173 BiConsumer<? super R,? super S> f,
1174 BiAccept<R,S> c) {
1175 Object r, s; Throwable x;
1176 if (a == null || (r = a.result) == null ||
1177 b == null || (s = b.result) == null || f == null)
1178 return false;
1179 tryComplete: if (result == null) {
1180 if (r instanceof AltResult) {
1181 if ((x = ((AltResult)r).ex) != null) {
1182 completeThrowable(x, r);
1183 break tryComplete;
1184 }
1185 r = null;
1186 }
1187 if (s instanceof AltResult) {
1188 if ((x = ((AltResult)s).ex) != null) {
1189 completeThrowable(x, s);
1190 break tryComplete;
1191 }
1192 s = null;
1193 }
1194 try {
1195 if (c != null && !c.claim())
1196 return false;
1197 @SuppressWarnings("unchecked") R rr = (R) r;
1198 @SuppressWarnings("unchecked") S ss = (S) s;
1199 f.accept(rr, ss);
1200 completeNull();
1201 } catch (Throwable ex) {
1202 completeThrowable(ex);
1203 }
1204 }
1205 return true;
1206 }
1207
1208 private <U> CompletableFuture<Void> biAcceptStage(
1209 Executor e, CompletionStage<U> o,
1210 BiConsumer<? super T,? super U> f) {
1211 CompletableFuture<U> b;
1212 if (f == null || (b = o.toCompletableFuture()) == null)
1213 throw new NullPointerException();
1214 CompletableFuture<Void> d = newIncompleteFuture();
1215 if (e != null || !d.biAccept(this, b, f, null)) {
1216 BiAccept<T,U> c = new BiAccept<T,U>(e, d, this, b, f);
1217 bipush(b, c);
1218 c.tryFire(SYNC);
1219 }
1220 return d;
1221 }
1222
1223 @SuppressWarnings("serial")
1224 static final class BiRun<T,U> extends BiCompletion<T,U,Void> {
1225 Runnable fn;
1226 BiRun(Executor executor, CompletableFuture<Void> dep,
1227 CompletableFuture<T> src,
1228 CompletableFuture<U> snd,
1229 Runnable fn) {
1230 super(executor, dep, src, snd); this.fn = fn;
1231 }
1232 final CompletableFuture<Void> tryFire(int mode) {
1233 CompletableFuture<Void> d;
1234 CompletableFuture<T> a;
1235 CompletableFuture<U> b;
1236 if ((d = dep) == null ||
1237 !d.biRun(a = src, b = snd, fn, mode > 0 ? null : this))
1238 return null;
1239 dep = null; src = null; snd = null; fn = null;
1240 return d.postFire(a, b, mode);
1241 }
1242 }
1243
1244 final boolean biRun(CompletableFuture<?> a, CompletableFuture<?> b,
1245 Runnable f, BiRun<?,?> c) {
1246 Object r, s; Throwable x;
1247 if (a == null || (r = a.result) == null ||
1248 b == null || (s = b.result) == null || f == null)
1249 return false;
1250 if (result == null) {
1251 if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
1252 completeThrowable(x, r);
1253 else if (s instanceof AltResult && (x = ((AltResult)s).ex) != null)
1254 completeThrowable(x, s);
1255 else
1256 try {
1257 if (c != null && !c.claim())
1258 return false;
1259 f.run();
1260 completeNull();
1261 } catch (Throwable ex) {
1262 completeThrowable(ex);
1263 }
1264 }
1265 return true;
1266 }
1267
1268 private CompletableFuture<Void> biRunStage(Executor e, CompletionStage<?> o,
1269 Runnable f) {
1270 CompletableFuture<?> b;
1271 if (f == null || (b = o.toCompletableFuture()) == null)
1272 throw new NullPointerException();
1273 CompletableFuture<Void> d = newIncompleteFuture();
1274 if (e != null || !d.biRun(this, b, f, null)) {
1275 BiRun<T,?> c = new BiRun<>(e, d, this, b, f);
1276 bipush(b, c);
1277 c.tryFire(SYNC);
1278 }
1279 return d;
1280 }
1281
1282 @SuppressWarnings("serial")
1283 static final class BiRelay<T,U> extends BiCompletion<T,U,Void> { // for And
1284 BiRelay(CompletableFuture<Void> dep,
1285 CompletableFuture<T> src,
1286 CompletableFuture<U> snd) {
1287 super(null, dep, src, snd);
1288 }
1289 final CompletableFuture<Void> tryFire(int mode) {
1290 CompletableFuture<Void> d;
1291 CompletableFuture<T> a;
1292 CompletableFuture<U> b;
1293 if ((d = dep) == null || !d.biRelay(a = src, b = snd))
1294 return null;
1295 src = null; snd = null; dep = null;
1296 return d.postFire(a, b, mode);
1297 }
1298 }
1299
1300 boolean biRelay(CompletableFuture<?> a, CompletableFuture<?> b) {
1301 Object r, s; Throwable x;
1302 if (a == null || (r = a.result) == null ||
1303 b == null || (s = b.result) == null)
1304 return false;
1305 if (result == null) {
1306 if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
1307 completeThrowable(x, r);
1308 else if (s instanceof AltResult && (x = ((AltResult)s).ex) != null)
1309 completeThrowable(x, s);
1310 else
1311 completeNull();
1312 }
1313 return true;
1314 }
1315
1316 /** Recursively constructs a tree of completions. */
1317 static CompletableFuture<Void> andTree(CompletableFuture<?>[] cfs,
1318 int lo, int hi) {
1319 CompletableFuture<Void> d = new CompletableFuture<Void>();
1320 if (lo > hi) // empty
1321 d.result = NIL;
1322 else {
1323 CompletableFuture<?> a, b;
1324 int mid = (lo + hi) >>> 1;
1325 if ((a = (lo == mid ? cfs[lo] :
1326 andTree(cfs, lo, mid))) == null ||
1327 (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
1328 andTree(cfs, mid+1, hi))) == null)
1329 throw new NullPointerException();
1330 if (!d.biRelay(a, b)) {
1331 BiRelay<?,?> c = new BiRelay<>(d, a, b);
1332 a.bipush(b, c);
1333 c.tryFire(SYNC);
1334 }
1335 }
1336 return d;
1337 }
1338
1339 /* ------------- Projected (Ored) BiCompletions -------------- */
1340
1341 /** Pushes completion to this and b unless either done. */
1342 final void orpush(CompletableFuture<?> b, BiCompletion<?,?,?> c) {
1343 if (c != null) {
1344 while ((b == null || b.result == null) && result == null) {
1345 if (tryPushStack(c)) {
1346 if (b != null && b != this && b.result == null) {
1347 Completion q = new CoCompletion(c);
1348 while (result == null && b.result == null &&
1349 !b.tryPushStack(q))
1350 lazySetNext(q, null); // clear on failure
1351 }
1352 break;
1353 }
1354 lazySetNext(c, null); // clear on failure
1355 }
1356 }
1357 }
1358
1359 @SuppressWarnings("serial")
1360 static final class OrApply<T,U extends T,V> extends BiCompletion<T,U,V> {
1361 Function<? super T,? extends V> fn;
1362 OrApply(Executor executor, CompletableFuture<V> dep,
1363 CompletableFuture<T> src,
1364 CompletableFuture<U> snd,
1365 Function<? super T,? extends V> fn) {
1366 super(executor, dep, src, snd); this.fn = fn;
1367 }
1368 final CompletableFuture<V> tryFire(int mode) {
1369 CompletableFuture<V> d;
1370 CompletableFuture<T> a;
1371 CompletableFuture<U> b;
1372 if ((d = dep) == null ||
1373 !d.orApply(a = src, b = snd, fn, mode > 0 ? null : this))
1374 return null;
1375 dep = null; src = null; snd = null; fn = null;
1376 return d.postFire(a, b, mode);
1377 }
1378 }
1379
1380 final <R,S extends R> boolean orApply(CompletableFuture<R> a,
1381 CompletableFuture<S> b,
1382 Function<? super R, ? extends T> f,
1383 OrApply<R,S,T> c) {
1384 Object r; Throwable x;
1385 if (a == null || b == null ||
1386 ((r = a.result) == null && (r = b.result) == null) || f == null)
1387 return false;
1388 tryComplete: if (result == null) {
1389 try {
1390 if (c != null && !c.claim())
1391 return false;
1392 if (r instanceof AltResult) {
1393 if ((x = ((AltResult)r).ex) != null) {
1394 completeThrowable(x, r);
1395 break tryComplete;
1396 }
1397 r = null;
1398 }
1399 @SuppressWarnings("unchecked") R rr = (R) r;
1400 completeValue(f.apply(rr));
1401 } catch (Throwable ex) {
1402 completeThrowable(ex);
1403 }
1404 }
1405 return true;
1406 }
1407
1408 private <U extends T,V> CompletableFuture<V> orApplyStage(
1409 Executor e, CompletionStage<U> o,
1410 Function<? super T, ? extends V> f) {
1411 CompletableFuture<U> b;
1412 if (f == null || (b = o.toCompletableFuture()) == null)
1413 throw new NullPointerException();
1414 CompletableFuture<V> d = newIncompleteFuture();
1415 if (e != null || !d.orApply(this, b, f, null)) {
1416 OrApply<T,U,V> c = new OrApply<T,U,V>(e, d, this, b, f);
1417 orpush(b, c);
1418 c.tryFire(SYNC);
1419 }
1420 return d;
1421 }
1422
1423 @SuppressWarnings("serial")
1424 static final class OrAccept<T,U extends T> extends BiCompletion<T,U,Void> {
1425 Consumer<? super T> fn;
1426 OrAccept(Executor executor, CompletableFuture<Void> dep,
1427 CompletableFuture<T> src,
1428 CompletableFuture<U> snd,
1429 Consumer<? super T> fn) {
1430 super(executor, dep, src, snd); this.fn = fn;
1431 }
1432 final CompletableFuture<Void> tryFire(int mode) {
1433 CompletableFuture<Void> d;
1434 CompletableFuture<T> a;
1435 CompletableFuture<U> b;
1436 if ((d = dep) == null ||
1437 !d.orAccept(a = src, b = snd, fn, mode > 0 ? null : this))
1438 return null;
1439 dep = null; src = null; snd = null; fn = null;
1440 return d.postFire(a, b, mode);
1441 }
1442 }
1443
1444 final <R,S extends R> boolean orAccept(CompletableFuture<R> a,
1445 CompletableFuture<S> b,
1446 Consumer<? super R> f,
1447 OrAccept<R,S> c) {
1448 Object r; Throwable x;
1449 if (a == null || b == null ||
1450 ((r = a.result) == null && (r = b.result) == null) || f == null)
1451 return false;
1452 tryComplete: if (result == null) {
1453 try {
1454 if (c != null && !c.claim())
1455 return false;
1456 if (r instanceof AltResult) {
1457 if ((x = ((AltResult)r).ex) != null) {
1458 completeThrowable(x, r);
1459 break tryComplete;
1460 }
1461 r = null;
1462 }
1463 @SuppressWarnings("unchecked") R rr = (R) r;
1464 f.accept(rr);
1465 completeNull();
1466 } catch (Throwable ex) {
1467 completeThrowable(ex);
1468 }
1469 }
1470 return true;
1471 }
1472
1473 private <U extends T> CompletableFuture<Void> orAcceptStage(
1474 Executor e, CompletionStage<U> o, Consumer<? super T> f) {
1475 CompletableFuture<U> b;
1476 if (f == null || (b = o.toCompletableFuture()) == null)
1477 throw new NullPointerException();
1478 CompletableFuture<Void> d = newIncompleteFuture();
1479 if (e != null || !d.orAccept(this, b, f, null)) {
1480 OrAccept<T,U> c = new OrAccept<T,U>(e, d, this, b, f);
1481 orpush(b, c);
1482 c.tryFire(SYNC);
1483 }
1484 return d;
1485 }
1486
1487 @SuppressWarnings("serial")
1488 static final class OrRun<T,U> extends BiCompletion<T,U,Void> {
1489 Runnable fn;
1490 OrRun(Executor executor, CompletableFuture<Void> dep,
1491 CompletableFuture<T> src,
1492 CompletableFuture<U> snd,
1493 Runnable fn) {
1494 super(executor, dep, src, snd); this.fn = fn;
1495 }
1496 final CompletableFuture<Void> tryFire(int mode) {
1497 CompletableFuture<Void> d;
1498 CompletableFuture<T> a;
1499 CompletableFuture<U> b;
1500 if ((d = dep) == null ||
1501 !d.orRun(a = src, b = snd, fn, mode > 0 ? null : this))
1502 return null;
1503 dep = null; src = null; snd = null; fn = null;
1504 return d.postFire(a, b, mode);
1505 }
1506 }
1507
1508 final boolean orRun(CompletableFuture<?> a, CompletableFuture<?> b,
1509 Runnable f, OrRun<?,?> c) {
1510 Object r; Throwable x;
1511 if (a == null || b == null ||
1512 ((r = a.result) == null && (r = b.result) == null) || f == null)
1513 return false;
1514 if (result == null) {
1515 try {
1516 if (c != null && !c.claim())
1517 return false;
1518 if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
1519 completeThrowable(x, r);
1520 else {
1521 f.run();
1522 completeNull();
1523 }
1524 } catch (Throwable ex) {
1525 completeThrowable(ex);
1526 }
1527 }
1528 return true;
1529 }
1530
1531 private CompletableFuture<Void> orRunStage(Executor e, CompletionStage<?> o,
1532 Runnable f) {
1533 CompletableFuture<?> b;
1534 if (f == null || (b = o.toCompletableFuture()) == null)
1535 throw new NullPointerException();
1536 CompletableFuture<Void> d = newIncompleteFuture();
1537 if (e != null || !d.orRun(this, b, f, null)) {
1538 OrRun<T,?> c = new OrRun<>(e, d, this, b, f);
1539 orpush(b, c);
1540 c.tryFire(SYNC);
1541 }
1542 return d;
1543 }
1544
1545 @SuppressWarnings("serial")
1546 static final class OrRelay<T,U> extends BiCompletion<T,U,Object> { // for Or
1547 OrRelay(CompletableFuture<Object> dep, CompletableFuture<T> src,
1548 CompletableFuture<U> snd) {
1549 super(null, dep, src, snd);
1550 }
1551 final CompletableFuture<Object> tryFire(int mode) {
1552 CompletableFuture<Object> d;
1553 CompletableFuture<T> a;
1554 CompletableFuture<U> b;
1555 if ((d = dep) == null || !d.orRelay(a = src, b = snd))
1556 return null;
1557 src = null; snd = null; dep = null;
1558 return d.postFire(a, b, mode);
1559 }
1560 }
1561
1562 final boolean orRelay(CompletableFuture<?> a, CompletableFuture<?> b) {
1563 Object r;
1564 if (a == null || b == null ||
1565 ((r = a.result) == null && (r = b.result) == null))
1566 return false;
1567 if (result == null)
1568 completeRelay(r);
1569 return true;
1570 }
1571
1572 /** Recursively constructs a tree of completions. */
1573 static CompletableFuture<Object> orTree(CompletableFuture<?>[] cfs,
1574 int lo, int hi) {
1575 CompletableFuture<Object> d = new CompletableFuture<Object>();
1576 if (lo <= hi) {
1577 CompletableFuture<?> a, b;
1578 int mid = (lo + hi) >>> 1;
1579 if ((a = (lo == mid ? cfs[lo] :
1580 orTree(cfs, lo, mid))) == null ||
1581 (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
1582 orTree(cfs, mid+1, hi))) == null)
1583 throw new NullPointerException();
1584 if (!d.orRelay(a, b)) {
1585 OrRelay<?,?> c = new OrRelay<>(d, a, b);
1586 a.orpush(b, c);
1587 c.tryFire(SYNC);
1588 }
1589 }
1590 return d;
1591 }
1592
1593 /* ------------- Zero-input Async forms -------------- */
1594
1595 @SuppressWarnings("serial")
1596 static final class AsyncSupply<T> extends ForkJoinTask<Void>
1597 implements Runnable, AsynchronousCompletionTask {
1598 CompletableFuture<T> dep; Supplier<? extends T> fn;
1599 AsyncSupply(CompletableFuture<T> dep, Supplier<? extends T> fn) {
1600 this.dep = dep; this.fn = fn;
1601 }
1602
1603 public final Void getRawResult() { return null; }
1604 public final void setRawResult(Void v) {}
1605 public final boolean exec() { run(); return true; }
1606
1607 public void run() {
1608 CompletableFuture<T> d; Supplier<? extends T> f;
1609 if ((d = dep) != null && (f = fn) != null) {
1610 dep = null; fn = null;
1611 if (d.result == null) {
1612 try {
1613 d.completeValue(f.get());
1614 } catch (Throwable ex) {
1615 d.completeThrowable(ex);
1616 }
1617 }
1618 d.postComplete();
1619 }
1620 }
1621 }
1622
1623 static <U> CompletableFuture<U> asyncSupplyStage(Executor e,
1624 Supplier<U> f) {
1625 if (f == null) throw new NullPointerException();
1626 CompletableFuture<U> d = new CompletableFuture<U>();
1627 e.execute(new AsyncSupply<U>(d, f));
1628 return d;
1629 }
1630
1631 @SuppressWarnings("serial")
1632 static final class AsyncRun extends ForkJoinTask<Void>
1633 implements Runnable, AsynchronousCompletionTask {
1634 CompletableFuture<Void> dep; Runnable fn;
1635 AsyncRun(CompletableFuture<Void> dep, Runnable fn) {
1636 this.dep = dep; this.fn = fn;
1637 }
1638
1639 public final Void getRawResult() { return null; }
1640 public final void setRawResult(Void v) {}
1641 public final boolean exec() { run(); return true; }
1642
1643 public void run() {
1644 CompletableFuture<Void> d; Runnable f;
1645 if ((d = dep) != null && (f = fn) != null) {
1646 dep = null; fn = null;
1647 if (d.result == null) {
1648 try {
1649 f.run();
1650 d.completeNull();
1651 } catch (Throwable ex) {
1652 d.completeThrowable(ex);
1653 }
1654 }
1655 d.postComplete();
1656 }
1657 }
1658 }
1659
1660 static CompletableFuture<Void> asyncRunStage(Executor e, Runnable f) {
1661 if (f == null) throw new NullPointerException();
1662 CompletableFuture<Void> d = new CompletableFuture<Void>();
1663 e.execute(new AsyncRun(d, f));
1664 return d;
1665 }
1666
1667 /* ------------- Signallers -------------- */
1668
1669 /**
1670 * Completion for recording and releasing a waiting thread. This
1671 * class implements ManagedBlocker to avoid starvation when
1672 * blocking actions pile up in ForkJoinPools.
1673 */
1674 @SuppressWarnings("serial")
1675 static final class Signaller extends Completion
1676 implements ForkJoinPool.ManagedBlocker {
1677 long nanos; // wait time if timed
1678 final long deadline; // non-zero if timed
1679 volatile int interruptControl; // > 0: interruptible, < 0: interrupted
1680 volatile Thread thread;
1681
1682 Signaller(boolean interruptible, long nanos, long deadline) {
1683 this.thread = Thread.currentThread();
1684 this.interruptControl = interruptible ? 1 : 0;
1685 this.nanos = nanos;
1686 this.deadline = deadline;
1687 }
1688 final CompletableFuture<?> tryFire(int ignore) {
1689 Thread w; // no need to atomically claim
1690 if ((w = thread) != null) {
1691 thread = null;
1692 LockSupport.unpark(w);
1693 }
1694 return null;
1695 }
1696 public boolean isReleasable() {
1697 if (thread == null)
1698 return true;
1699 if (Thread.interrupted()) {
1700 int i = interruptControl;
1701 interruptControl = -1;
1702 if (i > 0)
1703 return true;
1704 }
1705 if (deadline != 0L &&
1706 (nanos <= 0L || (nanos = deadline - System.nanoTime()) <= 0L)) {
1707 thread = null;
1708 return true;
1709 }
1710 return false;
1711 }
1712 public boolean block() {
1713 if (isReleasable())
1714 return true;
1715 else if (deadline == 0L)
1716 LockSupport.park(this);
1717 else if (nanos > 0L)
1718 LockSupport.parkNanos(this, nanos);
1719 return isReleasable();
1720 }
1721 final boolean isLive() { return thread != null; }
1722 }
1723
1724 /**
1725 * Returns raw result after waiting, or null if interruptible and
1726 * interrupted.
1727 */
1728 private Object waitingGet(boolean interruptible) {
1729 Signaller q = null;
1730 boolean queued = false;
1731 int spins = -1;
1732 Object r;
1733 while ((r = result) == null) {
1734 if (spins < 0)
1735 spins = (Runtime.getRuntime().availableProcessors() > 1) ?
1736 1 << 8 : 0; // Use brief spin-wait on multiprocessors
1737 else 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 if (interruptible && q.interruptControl < 0) {
1746 q.thread = null;
1747 cleanStack();
1748 return null;
1749 }
1750 else if (q.thread != null && result == null) {
1751 try {
1752 ForkJoinPool.managedBlock(q);
1753 } catch (InterruptedException ie) {
1754 q.interruptControl = -1;
1755 }
1756 }
1757 }
1758 if (q != null) {
1759 q.thread = null;
1760 if (q.interruptControl < 0) {
1761 if (interruptible)
1762 r = null; // report interruption
1763 else
1764 Thread.currentThread().interrupt();
1765 }
1766 }
1767 postComplete();
1768 return r;
1769 }
1770
1771 /**
1772 * Returns raw result after waiting, or null if interrupted, or
1773 * throws TimeoutException on timeout.
1774 */
1775 private Object timedGet(long nanos) throws TimeoutException {
1776 if (Thread.interrupted())
1777 return null;
1778 if (nanos <= 0L)
1779 throw new TimeoutException();
1780 long d = System.nanoTime() + nanos;
1781 Signaller q = new Signaller(true, nanos, d == 0L ? 1L : d); // avoid 0
1782 boolean queued = false;
1783 Object r;
1784 // We intentionally don't spin here (as waitingGet does) because
1785 // the call to nanoTime() above acts much like a spin.
1786 while ((r = result) == null) {
1787 if (!queued)
1788 queued = tryPushStack(q);
1789 else if (q.interruptControl < 0 || q.nanos <= 0L) {
1790 q.thread = null;
1791 cleanStack();
1792 if (q.interruptControl < 0)
1793 return null;
1794 throw new TimeoutException();
1795 }
1796 else if (q.thread != null && result == null) {
1797 try {
1798 ForkJoinPool.managedBlock(q);
1799 } catch (InterruptedException ie) {
1800 q.interruptControl = -1;
1801 }
1802 }
1803 }
1804 if (q.interruptControl < 0)
1805 r = null;
1806 q.thread = null;
1807 postComplete();
1808 return r;
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(asyncPool, 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(asyncPool, 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 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 asyncPool;
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 give base
2539 * executor after the given delay (or no delay if non-positive).
2540 * Each delay commences upon invocation of this Executor's {@code
2541 * 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 this Executor's {@code
2561 * 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, asyncPool);
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>(encodeThrowable(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>(encodeThrowable(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() { f.complete(u); }
2686 }
2687
2688 /** Action to cancel unneeded timeouts */
2689 static final class Canceller implements BiConsumer<Object, Throwable> {
2690 final Future<?> f;
2691 Canceller(Future<?> f) { this.f = f; }
2692 public void accept(Object ignore, Throwable ex) {
2693 if (ex == null && f != null && !f.isDone())
2694 f.cancel(false);
2695 }
2696 }
2697
2698 // MinimalStage subclass just throws UOE for non-CompletionStage methods
2699 static final class MinimalStage<T> extends CompletableFuture<T> {
2700 MinimalStage() { }
2701 MinimalStage(Object r) { super(r); }
2702 public <U> CompletableFuture<U> newIncompleteFuture() {
2703 return new MinimalStage<U>(); }
2704 public T get() {
2705 throw new UnsupportedOperationException(); }
2706 public T get(long timeout, TimeUnit unit) {
2707 throw new UnsupportedOperationException(); }
2708 public T getNow(T valueIfAbsent) {
2709 throw new UnsupportedOperationException(); }
2710 public T join() {
2711 throw new UnsupportedOperationException(); }
2712 public boolean complete(T value) {
2713 throw new UnsupportedOperationException(); }
2714 public boolean completeExceptionally(Throwable ex) {
2715 throw new UnsupportedOperationException(); }
2716 public boolean cancel(boolean mayInterruptIfRunning) {
2717 throw new UnsupportedOperationException(); }
2718 public void obtrudeValue(T value) {
2719 throw new UnsupportedOperationException(); }
2720 public void obtrudeException(Throwable ex) {
2721 throw new UnsupportedOperationException(); }
2722 public boolean isDone() {
2723 throw new UnsupportedOperationException(); }
2724 public boolean isCancelled() {
2725 throw new UnsupportedOperationException(); }
2726 public boolean isCompletedExceptionally() {
2727 throw new UnsupportedOperationException(); }
2728 public int getNumberOfDependents() {
2729 throw new UnsupportedOperationException(); }
2730 }
2731
2732 // Unsafe mechanics
2733 private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
2734 private static final long RESULT;
2735 private static final long STACK;
2736 private static final long NEXT;
2737 static {
2738 try {
2739 RESULT = U.objectFieldOffset
2740 (CompletableFuture.class.getDeclaredField("result"));
2741 STACK = U.objectFieldOffset
2742 (CompletableFuture.class.getDeclaredField("stack"));
2743 NEXT = U.objectFieldOffset
2744 (Completion.class.getDeclaredField("next"));
2745 } catch (ReflectiveOperationException e) {
2746 throw new Error(e);
2747 }
2748
2749 // Reduce the risk of rare disastrous classloading in first call to
2750 // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
2751 Class<?> ensureLoaded = LockSupport.class;
2752 }
2753 }