ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.201
Committed: Sun Jun 26 20:37:35 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.200: +195 -234 lines
Log Message:
improve efficiency of Uni/Or completions when immediately complete

File Contents

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