-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
CompletableFuture.java
3093 lines (2869 loc) · 115 KB
/
CompletableFuture.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent;
import jdk.internal.invoke.MhUtil;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.concurrent.locks.LockSupport;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.Objects;
/**
* A {@link Future} that may be explicitly completed (setting its
* value and status), and may be used as a {@link CompletionStage},
* supporting dependent functions and actions that trigger upon its
* completion.
*
* <p>When two or more threads attempt to
* {@link #complete complete},
* {@link #completeExceptionally completeExceptionally}, or
* {@link #cancel cancel}
* a CompletableFuture, only one of them succeeds.
*
* <p>In addition to these and related methods for directly
* manipulating status and results, CompletableFuture implements
* interface {@link CompletionStage} with the following policies: <ul>
*
* <li>Actions supplied for dependent completions of
* <em>non-async</em> methods may be performed by the thread that
* completes the current CompletableFuture, or by any other caller of
* a completion method.
*
* <li>All <em>async</em> methods without an explicit Executor
* argument are performed using the {@link ForkJoinPool#commonPool()}
* (unless it does not support a parallelism level of at least two, in
* which case, a new Thread is created to run each task). This may be
* overridden for non-static methods in subclasses by defining method
* {@link #defaultExecutor()}. To simplify monitoring, debugging,
* and tracking, all generated asynchronous tasks are instances of the
* marker interface {@link AsynchronousCompletionTask}. Operations
* with time-delays can use adapter methods defined in this class, for
* example: {@code supplyAsync(supplier, delayedExecutor(timeout,
* timeUnit))}. To support methods with delays and timeouts, this
* class maintains at most one daemon thread for triggering and
* cancelling actions, not for running them.
*
* <li>All CompletionStage methods are implemented independently of
* other public methods, so the behavior of one method is not impacted
* by overrides of others in subclasses.
*
* <li>All CompletionStage methods return CompletableFutures. To
* restrict usages to only those methods defined in interface
* CompletionStage, use method {@link #minimalCompletionStage}. Or to
* ensure only that clients do not themselves modify a future, use
* method {@link #copy}.
* </ul>
*
* <p>CompletableFuture also implements {@link Future} with the following
* policies: <ul>
*
* <li>Since (unlike {@link FutureTask}) this class has no direct
* control over the computation that causes it to be completed,
* cancellation is treated as just another form of exceptional
* completion. Method {@link #cancel cancel} has the same effect as
* {@code completeExceptionally(new CancellationException())}. Method
* {@link #isCompletedExceptionally} can be used to determine if a
* CompletableFuture completed in any exceptional fashion.
*
* <li>In case of exceptional completion with a CompletionException,
* methods {@link #get()} and {@link #get(long, TimeUnit)} throw an
* {@link ExecutionException} with the same cause as held in the
* corresponding CompletionException. To simplify usage in most
* contexts, this class also defines methods {@link #join()} and
* {@link #getNow} that instead throw the CompletionException directly
* in these cases.
* </ul>
*
* <p>Arguments used to pass a completion result (that is, for
* parameters of type {@code T}) for methods accepting them may be
* null, but passing a null value for any other parameter will result
* in a {@link NullPointerException} being thrown.
*
* <p>Subclasses of this class should normally override the "virtual
* constructor" method {@link #newIncompleteFuture}, which establishes
* the concrete type returned by CompletionStage methods. For example,
* here is a class that substitutes a different default Executor and
* disables the {@code obtrude} methods:
*
* <pre> {@code
* class MyCompletableFuture<T> extends CompletableFuture<T> {
* static final Executor myExecutor = ...;
* public MyCompletableFuture() { }
* public <U> CompletableFuture<U> newIncompleteFuture() {
* return new MyCompletableFuture<U>(); }
* public Executor defaultExecutor() {
* return myExecutor; }
* public void obtrudeValue(T value) {
* throw new UnsupportedOperationException(); }
* public void obtrudeException(Throwable ex) {
* throw new UnsupportedOperationException(); }
* }}</pre>
*
* @author Doug Lea
* @param <T> The result type returned by this future's {@code join}
* and {@code get} methods
* @since 1.8
*/
public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {
/*
* Overview:
*
* A CompletableFuture may have dependent completion actions,
* collected in a linked stack. It atomically completes by CASing
* a result field, and then pops off and runs those actions. This
* applies across normal vs exceptional outcomes, sync vs async
* actions, binary triggers, and various forms of completions.
*
* Non-nullness of volatile field "result" indicates done. It may
* be set directly if known to be thread-confined, else via CAS.
* An AltResult is used to box null as a result, as well as to
* hold exceptions. Using a single field makes completion simple
* to detect and trigger. Result encoding and decoding is
* straightforward but tedious and adds to the sprawl of trapping
* and associating exceptions with targets. Minor simplifications
* rely on (static) NIL (to box null results) being the only
* AltResult with a null exception field, so we don't usually need
* explicit comparisons. Even though some of the generics casts
* are unchecked (see SuppressWarnings annotations), they are
* placed to be appropriate even if checked.
*
* Dependent actions are represented by Completion objects linked
* as Treiber stacks headed by field "stack". There are Completion
* classes for each kind of action, grouped into:
* - single-input (UniCompletion),
* - two-input (BiCompletion),
* - projected (BiCompletions using exactly one of two inputs),
* - shared (CoCompletion, used by the second of two sources),
* - zero-input source actions,
* - Signallers that unblock waiters.
* Class Completion extends ForkJoinTask to enable async execution
* (adding no space overhead because we exploit its "tag" methods
* to maintain claims). It is also declared as Runnable to allow
* usage with arbitrary executors.
*
* Support for each kind of CompletionStage relies on a separate
* class, along with two CompletableFuture methods:
*
* * A Completion class with name X corresponding to function,
* prefaced with "Uni", "Bi", or "Or". Each class contains
* fields for source(s), actions, and dependent. They are
* boringly similar, differing from others only with respect to
* underlying functional forms. We do this so that users don't
* encounter layers of adapters in common usages.
*
* * Boolean CompletableFuture method x(...) (for example
* biApply) takes all of the arguments needed to check that an
* action is triggerable, and then either runs the action or
* arranges its async execution by executing its Completion
* argument, if present. The method returns true if known to be
* complete.
*
* * Completion method tryFire(int mode) invokes the associated x
* method with its held arguments, and on success cleans up.
* The mode argument allows tryFire to be called twice (SYNC,
* then ASYNC); the first to screen and trap exceptions while
* arranging to execute, and the second when called from a task.
* (A few classes are not used async so take slightly different
* forms.) The claim() callback suppresses function invocation
* if already claimed by another thread.
*
* * Some classes (for example UniApply) have separate handling
* code for when known to be thread-confined ("now" methods) and
* for when shared (in tryFire), for efficiency.
*
* * CompletableFuture method xStage(...) is called from a public
* stage method of CompletableFuture f. It screens user
* arguments and invokes and/or creates the stage object. If
* not async and already triggerable, the action is run
* immediately. Otherwise a Completion c is created, and
* submitted to the executor if triggerable, or pushed onto f's
* stack if not. Completion actions are started via c.tryFire.
* We recheck after pushing to a source future's stack to cover
* possible races if the source completes while pushing.
* Classes with two inputs (for example BiApply) deal with races
* across both while pushing actions. The second completion is
* a CoCompletion pointing to the first, shared so that at most
* one performs the action. The multiple-arity methods allOf
* does this pairwise to form trees of completions. Method
* anyOf is handled differently from allOf because completion of
* any source should trigger a cleanStack of other sources.
* Each AnyOf completion can reach others via a shared array.
*
* Note that the generic type parameters of methods vary according
* to whether "this" is a source, dependent, or completion.
*
* Method postComplete is called upon completion unless the target
* is guaranteed not to be observable (i.e., not yet returned or
* linked). Multiple threads can call postComplete, which
* atomically pops each dependent action, and tries to trigger it
* via method tryFire, in NESTED mode. Triggering can propagate
* recursively, so NESTED mode returns its completed dependent (if
* one exists) for further processing by its caller (see method
* postFire).
*
* Blocking methods get() and join() rely on Signaller Completions
* that wake up waiting threads. The mechanics are similar to
* Treiber stack wait-nodes used in FutureTask, Phaser, and
* SynchronousQueue. See their internal documentation for
* algorithmic details.
*
* Without precautions, CompletableFutures would be prone to
* garbage accumulation as chains of Completions build up, each
* pointing back to its sources. So we null out fields as soon as
* possible. The screening checks needed anyway harmlessly ignore
* null arguments that may have been obtained during races with
* threads nulling out fields. We also try to unlink non-isLive
* (fired or cancelled) Completions from stacks that might
* otherwise never be popped: Method cleanStack always unlinks non
* isLive completions from the head of stack; others may
* occasionally remain if racing with other cancellations or
* removals.
*
* Completion fields need not be declared as final or volatile
* because they are only visible to other threads upon safe
* publication.
*/
volatile Object result; // Either the result or boxed AltResult
volatile Completion stack; // Top of Treiber stack of dependent actions
final boolean internalComplete(Object r) { // CAS from null to r
return RESULT.compareAndSet(this, null, r);
}
/** Returns true if successfully pushed c onto stack. */
final boolean tryPushStack(Completion c) {
Completion h = stack;
NEXT.set(c, h); // CAS piggyback
return STACK.compareAndSet(this, h, c);
}
/** Unconditionally pushes c onto stack, retrying if necessary. */
final void pushStack(Completion c) {
do {} while (!tryPushStack(c));
}
/* ------------- Encoding and decoding outcomes -------------- */
static final class AltResult { // See above
final Throwable ex; // null only for NIL
AltResult(Throwable x) { this.ex = x; }
}
/** The encoding of the null value. */
static final AltResult NIL = new AltResult(null);
/** Completes with the null value, unless already completed. */
final boolean completeNull() {
return RESULT.compareAndSet(this, null, NIL);
}
/** Returns the encoding of the given non-exceptional value. */
final Object encodeValue(T t) {
return (t == null) ? NIL : t;
}
/** Completes with a non-exceptional result, unless already completed. */
final boolean completeValue(T t) {
return RESULT.compareAndSet(this, null, (t == null) ? NIL : t);
}
static CompletionException wrapInCompletionException(Throwable t) {
if (t == null)
return new CompletionException();
String message;
Throwable suppressed;
try {
message = t.toString();
suppressed = null;
} catch (Throwable unknown) {
message = "";
suppressed = unknown;
}
final CompletionException wrapping = new CompletionException(message, t);
if (suppressed != null)
wrapping.addSuppressed(suppressed);
return wrapping;
}
static ExecutionException wrapInExecutionException(Throwable t) {
if (t == null)
return new ExecutionException();
String message;
Throwable suppressed;
try {
message = t.toString();
suppressed = null;
} catch (Throwable unknown) {
message = "";
suppressed = unknown;
}
final ExecutionException wrapping = new ExecutionException(message, t);
if (suppressed != null)
wrapping.addSuppressed(suppressed);
return wrapping;
}
/**
* Returns the encoding of the given (non-null) exception as a
* wrapped CompletionException unless it is one already.
*/
static AltResult encodeThrowable(Throwable x) {
return new AltResult((x instanceof CompletionException) ? x :
wrapInCompletionException(x));
}
/** Completes with an exceptional result, unless already completed. */
final boolean completeThrowable(Throwable x) {
return RESULT.compareAndSet(this, null, encodeThrowable(x));
}
/**
* Returns the encoding of the given (non-null) exception as a
* wrapped CompletionException unless it is one already. May
* return the given Object r (which must have been the result of a
* source future) if it is equivalent, i.e. if this is a simple
* relay of an existing CompletionException.
*/
static Object encodeThrowable(Throwable x, Object r) {
if (!(x instanceof CompletionException))
x = wrapInCompletionException(x);
else if (r instanceof AltResult && x == ((AltResult)r).ex)
return r;
return new AltResult(x);
}
/**
* Completes with the given (non-null) exceptional result as a
* wrapped CompletionException unless it is one already, unless
* already completed. May complete with the given Object r
* (which must have been the result of a source future) if it is
* equivalent, i.e. if this is a simple propagation of an
* existing CompletionException.
*/
final boolean completeThrowable(Throwable x, Object r) {
return RESULT.compareAndSet(this, null, encodeThrowable(x, r));
}
/**
* Returns the encoding of the given arguments: if the exception
* is non-null, encodes as AltResult. Otherwise uses the given
* value, boxed as NIL if null.
*/
Object encodeOutcome(T t, Throwable x) {
return (x == null) ? (t == null) ? NIL : t : encodeThrowable(x);
}
/**
* Returns the encoding of a copied outcome; if exceptional,
* rewraps as a CompletionException, else returns argument.
*/
static Object encodeRelay(Object r) {
Throwable x;
if (r instanceof AltResult
&& (x = ((AltResult)r).ex) != null
&& !(x instanceof CompletionException))
r = new AltResult(wrapInCompletionException(x));
return r;
}
/**
* Completes with r or a copy of r, unless already completed.
* If exceptional, r is first coerced to a CompletionException.
*/
final boolean completeRelay(Object r) {
return RESULT.compareAndSet(this, null, encodeRelay(r));
}
/**
* Reports result using Future.get conventions.
*/
private static Object reportGet(Object r, String details)
throws InterruptedException, ExecutionException {
if (r == null) // by convention below, null means interrupted
throw new InterruptedException();
if (r instanceof AltResult) {
Throwable x, cause;
if ((x = ((AltResult)r).ex) == null)
return null;
if (x instanceof CancellationException)
throw new CancellationException(details, (CancellationException)x);
if ((x instanceof CompletionException) &&
(cause = x.getCause()) != null)
x = cause;
throw wrapInExecutionException(x);
}
return r;
}
/**
* Decodes outcome to return result or throw unchecked exception.
*/
private static Object reportJoin(Object r, String details) {
if (r instanceof AltResult) {
Throwable x;
if ((x = ((AltResult)r).ex) == null)
return null;
if (x instanceof CancellationException)
throw new CancellationException(details, (CancellationException)x);
if (x instanceof CompletionException)
throw (CompletionException)x;
throw wrapInCompletionException(x);
}
return r;
}
/* ------------- Async task preliminaries -------------- */
/**
* A marker interface identifying asynchronous tasks produced by
* {@code async} methods. This may be useful for monitoring,
* debugging, and tracking asynchronous activities.
*
* @since 1.8
*/
public static interface AsynchronousCompletionTask {
}
private static final boolean USE_COMMON_POOL =
(ForkJoinPool.getCommonPoolParallelism() > 1);
/**
* Default executor -- ForkJoinPool.commonPool() unless it cannot
* support parallelism.
*/
private static final Executor ASYNC_POOL = USE_COMMON_POOL ?
ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
/** Fallback if ForkJoinPool.commonPool() cannot support parallelism */
private static final class ThreadPerTaskExecutor implements Executor {
public void execute(Runnable r) {
Objects.requireNonNull(r);
new Thread(r).start();
}
}
/**
* Null-checks user executor argument, and translates uses of
* commonPool to ASYNC_POOL in case parallelism disabled.
*/
static Executor screenExecutor(Executor e) {
if (!USE_COMMON_POOL && e == ForkJoinPool.commonPool())
return ASYNC_POOL;
if (e == null) throw new NullPointerException();
return e;
}
// Modes for Completion.tryFire. Signedness matters.
static final int SYNC = 0;
static final int ASYNC = 1;
static final int NESTED = -1;
/* ------------- Base Completion classes and operations -------------- */
@SuppressWarnings("serial")
abstract static class Completion extends ForkJoinTask<Void>
implements Runnable, AsynchronousCompletionTask {
volatile Completion next; // Treiber stack link
/**
* Performs completion action if triggered, returning a
* dependent that may need propagation, if one exists.
*
* @param mode SYNC, ASYNC, or NESTED
*/
abstract CompletableFuture<?> tryFire(int mode);
/** Returns true if possibly still triggerable. Used by cleanStack. */
abstract boolean isLive();
public final void run() { tryFire(ASYNC); }
public final boolean exec() { tryFire(ASYNC); return false; }
public final Void getRawResult() { return null; }
public final void setRawResult(Void v) {}
}
/**
* Pops and tries to trigger all reachable dependents. Call only
* when known to be done.
*/
final void postComplete() {
/*
* On each step, variable f holds current dependents to pop
* and run. It is extended along only one path at a time,
* pushing others to avoid unbounded recursion.
*/
CompletableFuture<?> f = this; Completion h;
while ((h = f.stack) != null ||
(f != this && (h = (f = this).stack) != null)) {
CompletableFuture<?> d; Completion t;
if (STACK.compareAndSet(f, h, t = h.next)) {
if (t != null) {
if (f != this) {
pushStack(h);
continue;
}
NEXT.compareAndSet(h, t, null); // try to detach
}
f = (d = h.tryFire(NESTED)) == null ? this : d;
}
}
}
/** Traverses stack and unlinks one or more dead Completions, if found. */
final void cleanStack() {
Completion p = stack;
// ensure head of stack live
for (boolean unlinked = false;;) {
if (p == null)
return;
else if (p.isLive()) {
if (unlinked)
return;
else
break;
}
else if (STACK.weakCompareAndSet(this, p, (p = p.next)))
unlinked = true;
else
p = stack;
}
// try to unlink first non-live
for (Completion q = p.next; q != null;) {
Completion s = q.next;
if (q.isLive()) {
p = q;
q = s;
} else if (NEXT.weakCompareAndSet(p, q, s))
break;
else
q = p.next;
}
}
/* ------------- One-input Completions -------------- */
/** A Completion with a source, dependent, and executor. */
@SuppressWarnings("serial")
abstract static class UniCompletion<T,V> extends Completion {
Executor executor; // executor to use (null if none)
CompletableFuture<V> dep; // the dependent to complete
CompletableFuture<T> src; // source for action
UniCompletion(Executor executor, CompletableFuture<V> dep,
CompletableFuture<T> src) {
this.executor = executor; this.dep = dep; this.src = src;
}
/**
* Returns true if action can be run. Call only when known to
* be triggerable. Uses FJ tag bit to ensure that only one
* thread claims ownership. If async, starts as task -- a
* later call to tryFire will run action.
*/
final boolean claim() {
Executor e = executor;
if (compareAndSetForkJoinTaskTag((short)0, (short)1)) {
if (e == null)
return true;
executor = null; // disable
e.execute(this);
}
return false;
}
final boolean isLive() { return dep != null; }
}
/**
* Pushes the given completion unless it completes while trying.
* Caller should first check that result is null.
*/
final void unipush(Completion c) {
if (c != null) {
while (!tryPushStack(c)) {
if (result != null) {
NEXT.set(c, null);
break;
}
}
if (result != null)
c.tryFire(SYNC);
}
}
/**
* Post-processing by dependent after successful UniCompletion tryFire.
* Tries to clean stack of source a, and then either runs postComplete
* or returns this to caller, depending on mode.
*/
final CompletableFuture<T> postFire(CompletableFuture<?> a, int mode) {
if (a != null && a.stack != null) {
Object r;
if ((r = a.result) == null)
a.cleanStack();
if (mode >= 0 && (r != null || a.result != null))
a.postComplete();
}
if (result != null && stack != null) {
if (mode < 0)
return this;
else
postComplete();
}
return null;
}
@SuppressWarnings("serial")
static final class UniApply<T,V> extends UniCompletion<T,V> {
Function<? super T,? extends V> fn;
UniApply(Executor executor, CompletableFuture<V> dep,
CompletableFuture<T> src,
Function<? super T,? extends V> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture<V> tryFire(int mode) {
CompletableFuture<V> d; CompletableFuture<T> a;
Object r; Throwable x; Function<? super T,? extends V> f;
if ((a = src) == null || (r = a.result) == null
|| (d = dep) == null || (f = fn) == null)
return null;
tryComplete: if (d.result == null) {
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.completeThrowable(x, r);
break tryComplete;
}
r = null;
}
try {
if (mode <= 0 && !claim())
return null;
else {
@SuppressWarnings("unchecked") T t = (T) r;
d.completeValue(f.apply(t));
}
} catch (Throwable ex) {
d.completeThrowable(ex);
}
}
src = null; dep = null; fn = null;
return d.postFire(a, mode);
}
}
private <V> CompletableFuture<V> uniApplyStage(
Executor e, Function<? super T,? extends V> f) {
if (f == null) throw new NullPointerException();
Object r;
if ((r = result) != null)
return uniApplyNow(r, e, f);
CompletableFuture<V> d = newIncompleteFuture();
unipush(new UniApply<T,V>(e, d, this, f));
return d;
}
private <V> CompletableFuture<V> uniApplyNow(
Object r, Executor e, Function<? super T,? extends V> f) {
Throwable x;
CompletableFuture<V> d = newIncompleteFuture();
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.result = encodeThrowable(x, r);
return d;
}
r = null;
}
try {
if (e != null) {
e.execute(new UniApply<T,V>(null, d, this, f));
} else {
@SuppressWarnings("unchecked") T t = (T) r;
d.result = d.encodeValue(f.apply(t));
}
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
return d;
}
@SuppressWarnings("serial")
static final class UniAccept<T> extends UniCompletion<T,Void> {
Consumer<? super T> fn;
UniAccept(Executor executor, CompletableFuture<Void> dep,
CompletableFuture<T> src, Consumer<? super T> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture<Void> tryFire(int mode) {
CompletableFuture<Void> d; CompletableFuture<T> a;
Object r; Throwable x; Consumer<? super T> f;
if ((a = src) == null || (r = a.result) == null
|| (d = dep) == null || (f = fn) == null)
return null;
tryComplete: if (d.result == null) {
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.completeThrowable(x, r);
break tryComplete;
}
r = null;
}
try {
if (mode <= 0 && !claim())
return null;
else {
@SuppressWarnings("unchecked") T t = (T) r;
f.accept(t);
d.completeNull();
}
} catch (Throwable ex) {
d.completeThrowable(ex);
}
}
src = null; dep = null; fn = null;
return d.postFire(a, mode);
}
}
private CompletableFuture<Void> uniAcceptStage(Executor e,
Consumer<? super T> f) {
if (f == null) throw new NullPointerException();
Object r;
if ((r = result) != null)
return uniAcceptNow(r, e, f);
CompletableFuture<Void> d = newIncompleteFuture();
unipush(new UniAccept<T>(e, d, this, f));
return d;
}
private CompletableFuture<Void> uniAcceptNow(
Object r, Executor e, Consumer<? super T> f) {
Throwable x;
CompletableFuture<Void> d = newIncompleteFuture();
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
d.result = encodeThrowable(x, r);
return d;
}
r = null;
}
try {
if (e != null) {
e.execute(new UniAccept<T>(null, d, this, f));
} else {
@SuppressWarnings("unchecked") T t = (T) r;
f.accept(t);
d.result = NIL;
}
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
return d;
}
@SuppressWarnings("serial")
static final class UniRun<T> extends UniCompletion<T,Void> {
Runnable fn;
UniRun(Executor executor, CompletableFuture<Void> dep,
CompletableFuture<T> src, Runnable fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture<Void> tryFire(int mode) {
CompletableFuture<Void> d; CompletableFuture<T> a;
Object r; Throwable x; Runnable f;
if ((a = src) == null || (r = a.result) == null
|| (d = dep) == null || (f = fn) == null)
return null;
if (d.result == null) {
if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
d.completeThrowable(x, r);
else
try {
if (mode <= 0 && !claim())
return null;
else {
f.run();
d.completeNull();
}
} catch (Throwable ex) {
d.completeThrowable(ex);
}
}
src = null; dep = null; fn = null;
return d.postFire(a, mode);
}
}
private CompletableFuture<Void> uniRunStage(Executor e, Runnable f) {
if (f == null) throw new NullPointerException();
Object r;
if ((r = result) != null)
return uniRunNow(r, e, f);
CompletableFuture<Void> d = newIncompleteFuture();
unipush(new UniRun<T>(e, d, this, f));
return d;
}
private CompletableFuture<Void> uniRunNow(Object r, Executor e, Runnable f) {
Throwable x;
CompletableFuture<Void> d = newIncompleteFuture();
if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
d.result = encodeThrowable(x, r);
else
try {
if (e != null) {
e.execute(new UniRun<T>(null, d, this, f));
} else {
f.run();
d.result = NIL;
}
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
return d;
}
@SuppressWarnings("serial")
static final class UniWhenComplete<T> extends UniCompletion<T,T> {
BiConsumer<? super T, ? super Throwable> fn;
UniWhenComplete(Executor executor, CompletableFuture<T> dep,
CompletableFuture<T> src,
BiConsumer<? super T, ? super Throwable> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture<T> tryFire(int mode) {
CompletableFuture<T> d; CompletableFuture<T> a;
Object r; BiConsumer<? super T, ? super Throwable> f;
if ((a = src) == null || (r = a.result) == null
|| (d = dep) == null || (f = fn) == null
|| !d.uniWhenComplete(r, f, mode > 0 ? null : this))
return null;
src = null; dep = null; fn = null;
return d.postFire(a, mode);
}
}
final boolean uniWhenComplete(Object r,
BiConsumer<? super T,? super Throwable> f,
UniWhenComplete<T> c) {
T t; Throwable x = null;
if (result == null) {
try {
if (c != null && !c.claim())
return false;
if (r instanceof AltResult) {
x = ((AltResult)r).ex;
t = null;
} else {
@SuppressWarnings("unchecked") T tr = (T) r;
t = tr;
}
f.accept(t, x);
if (x == null) {
internalComplete(r);
return true;
}
} catch (Throwable ex) {
if (x == null)
x = ex;
else if (x != ex)
x.addSuppressed(ex);
}
completeThrowable(x, r);
}
return true;
}
private CompletableFuture<T> uniWhenCompleteStage(
Executor e, BiConsumer<? super T, ? super Throwable> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<T> d = newIncompleteFuture();
Object r;
if ((r = result) == null)
unipush(new UniWhenComplete<T>(e, d, this, f));
else if (e == null)
d.uniWhenComplete(r, f, null);
else {
try {
e.execute(new UniWhenComplete<T>(null, d, this, f));
} catch (Throwable ex) {
d.result = encodeThrowable(ex);
}
}
return d;
}
@SuppressWarnings("serial")
static final class UniHandle<T,V> extends UniCompletion<T,V> {
BiFunction<? super T, Throwable, ? extends V> fn;
UniHandle(Executor executor, CompletableFuture<V> dep,
CompletableFuture<T> src,
BiFunction<? super T, Throwable, ? extends V> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture<V> tryFire(int mode) {
CompletableFuture<V> d; CompletableFuture<T> a;
Object r; BiFunction<? super T, Throwable, ? extends V> f;
if ((a = src) == null || (r = a.result) == null
|| (d = dep) == null || (f = fn) == null
|| !d.uniHandle(r, f, mode > 0 ? null : this))
return null;
src = null; dep = null; fn = null;
return d.postFire(a, mode);
}
}
final <S> boolean uniHandle(Object r,
BiFunction<? super S, Throwable, ? extends T> f,
UniHandle<S,T> c) {
S s; Throwable x;
if (result == null) {
try {
if (c != null && !c.claim())
return false;
if (r instanceof AltResult) {
x = ((AltResult)r).ex;
s = null;
} else {
x = null;
@SuppressWarnings("unchecked") S ss = (S) r;
s = ss;
}
completeValue(f.apply(s, x));
} catch (Throwable ex) {
completeThrowable(ex);
}
}
return true;
}
private <V> CompletableFuture<V> uniHandleStage(
Executor e, BiFunction<? super T, Throwable, ? extends V> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<V> d = newIncompleteFuture();
Object r;
if ((r = result) == null)
unipush(new UniHandle<T,V>(e, d, this, f));
else if (e == null)
d.uniHandle(r, f, null);
else {
try {
e.execute(new UniHandle<T,V>(null, d, this, f));
} catch (Throwable ex) {