ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.155
Committed: Thu Jan 15 17:46:07 2015 UTC (9 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.154: +1 -0 lines
Log Message:
add class-level @param <T>

File Contents

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