ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CompletableFuture.java
Revision: 1.125
Committed: Sat May 31 05:52:50 2014 UTC (10 years ago) by jsr166
Branch: MAIN
Changes since 1.124: +33 -33 lines
Log Message:
better variable names

File Contents

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