forked from hazelcast/hazelcast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractInvocationFuture.java
1921 lines (1731 loc) · 72.3 KB
/
AbstractInvocationFuture.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
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.spi.impl;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.HazelcastException;
import com.hazelcast.core.OperationTimeoutException;
import com.hazelcast.instance.impl.OutOfMemoryErrorDispatcher;
import com.hazelcast.internal.util.executor.UnblockableThread;
import com.hazelcast.logging.ILogger;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
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 static com.hazelcast.internal.util.ConcurrencyUtil.DEFAULT_ASYNC_EXECUTOR;
import static com.hazelcast.internal.util.ExceptionUtil.sneakyThrow;
import static com.hazelcast.internal.util.ExceptionUtil.wrapError;
import static com.hazelcast.internal.util.ExceptionUtil.wrapException;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater;
import static java.util.concurrent.locks.LockSupport.park;
import static java.util.concurrent.locks.LockSupport.parkNanos;
import static java.util.concurrent.locks.LockSupport.unpark;
/**
* Custom implementation of {@link java.util.concurrent.CompletableFuture}.
*
* @param <V>
*/
@SuppressFBWarnings(value = "DLS_DEAD_STORE_OF_CLASS_LITERAL", justification = "Recommended way to prevent classloading bug")
@SuppressWarnings({"checkstyle:methodcount", "checkstyle:ClassDataAbstractionCoupling", "checkstyle:ClassFanOutComplexity"})
public abstract class AbstractInvocationFuture<V> extends InternalCompletableFuture<V> {
static final Object UNRESOLVED = new Object() {
@Override
public String toString() {
return "UNRESOLVED";
}
};
private static final AtomicReferenceFieldUpdater<AbstractInvocationFuture, Object> STATE_UPDATER =
newUpdater(AbstractInvocationFuture.class, Object.class, "state");
// reduce the risk of rare disastrous classloading in first call to
// LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
static {
@SuppressWarnings("unused")
Class<?> ensureLoaded = LockSupport.class;
}
protected final ILogger logger;
/**
* This field contains the state of the future. If the future is not
* complete, the state can be:
* <ol>
* <li>{@link #UNRESOLVED}: no response is available.</li>
* <li>Thread instance: no response is available and a thread has
* blocked on completion (e.g. future.get)</li>
* <li>{@link WaitNode} or {@link Waiter} instance: in case of multiple
* callback registrations or future.gets.</li>
* </ol>
* If the state is anything else, it is completed.
* <p>
* The reason why a single future.get or registered ExecutionCallback
* doesn't create a WaitNode is that we don't want to cause additional
* litter since most of our API calls are a get or a single ExecutionCallback.
* <p>
* The state field is replaced using a cas, so registration or setting a
* response is an atomic operation and therefore not prone to data-races.
* There is no need to use synchronized blocks.
*/
protected volatile Object state = UNRESOLVED;
protected AbstractInvocationFuture(@Nonnull ILogger logger) {
this.logger = logger;
}
// methods to be overridden
protected abstract String invocationToString();
// invokes resolve(value), then handles outcome with get() exception throwing conventions
protected abstract V resolveAndThrowIfException(Object state) throws ExecutionException, InterruptedException;
protected abstract TimeoutException newTimeoutException(long timeout, TimeUnit unit);
// CompletionStage API implementation
@Override
public <U> InternalCompletableFuture<U> thenApply(@Nonnull Function<? super V, ? extends U> fn) {
return thenApplyAsync(fn, defaultExecutor());
}
@Override
public <U> InternalCompletableFuture<U> thenApplyAsync(@Nonnull Function<? super V, ? extends U> fn) {
return thenApplyAsync(fn, defaultExecutor());
}
@Override
public <U> InternalCompletableFuture<U> thenApplyAsync(@Nonnull Function<? super V, ? extends U> fn, Executor executor) {
requireNonNull(fn);
requireNonNull(executor);
final InternalCompletableFuture<U> future = newCompletableFuture();
if (isDone()) {
unblockApply(fn, executor, future);
} else {
Object result = registerWaiter(new ApplyNode(future, fn), executor);
if (result != UNRESOLVED) {
unblockApply(fn, executor, future);
}
}
return future;
}
@Override
public InternalCompletableFuture<Void> thenAccept(@Nonnull Consumer<? super V> action) {
return thenAcceptAsync(action, defaultExecutor());
}
@Override
public InternalCompletableFuture<Void> thenAcceptAsync(@Nonnull Consumer<? super V> action) {
return thenAcceptAsync(action, defaultExecutor());
}
@Override
public InternalCompletableFuture<Void> thenAcceptAsync(@Nonnull Consumer<? super V> action,
@Nonnull Executor executor) {
requireNonNull(action);
requireNonNull(executor);
final InternalCompletableFuture<Void> future = newCompletableFuture();
if (isDone()) {
unblockAccept(action, executor, future);
} else {
Object result = registerWaiter(new AcceptNode<>(future, action), executor);
if (result != UNRESOLVED) {
unblockAccept(action, executor, future);
}
}
return future;
}
@Override
public InternalCompletableFuture<Void> thenRun(@Nonnull Runnable action) {
return thenRunAsync(action, defaultExecutor());
}
@Override
public InternalCompletableFuture<Void> thenRunAsync(@Nonnull Runnable action) {
return thenRunAsync(action, defaultExecutor());
}
@Override
public InternalCompletableFuture<Void> thenRunAsync(@Nonnull Runnable action, @Nonnull Executor executor) {
requireNonNull(action);
requireNonNull(executor);
final InternalCompletableFuture<Void> future = newCompletableFuture();
if (isDone()) {
unblockRun(action, executor, future);
} else {
Object result = registerWaiter(new RunNode(future, action), executor);
if (result != UNRESOLVED) {
unblockRun(action, executor, future);
}
}
return future;
}
@Override
public <U> InternalCompletableFuture<U> handle(@Nonnull BiFunction<? super V, Throwable, ? extends U> fn) {
return handleAsync(fn, defaultExecutor());
}
@Override
public <U> InternalCompletableFuture<U> handleAsync(@Nonnull BiFunction<? super V, Throwable, ? extends U> fn) {
return handleAsync(fn, defaultExecutor());
}
@Override
public <U> InternalCompletableFuture<U> handleAsync(@Nonnull BiFunction<? super V, Throwable, ? extends U> fn,
@Nonnull Executor executor) {
requireNonNull(fn);
requireNonNull(executor);
final InternalCompletableFuture<U> future = newCompletableFuture();
if (isDone()) {
unblockHandle(fn, executor, future);
} else {
Object result = registerWaiter(new HandleNode(future, fn), executor);
if (result != UNRESOLVED) {
unblockHandle(fn, executor, future);
}
}
return future;
}
@Override
public InternalCompletableFuture<V> whenComplete(@Nonnull BiConsumer<? super V, ? super Throwable> action) {
return whenCompleteAsync(action, defaultExecutor());
}
@Override
public InternalCompletableFuture<V> whenCompleteAsync(@Nonnull BiConsumer<? super V, ? super Throwable> action) {
return whenCompleteAsync(action, defaultExecutor());
}
@Override
public InternalCompletableFuture<V> whenCompleteAsync(@Nonnull BiConsumer<? super V, ? super Throwable> action,
@Nonnull Executor executor) {
requireNonNull(action);
requireNonNull(executor);
final InternalCompletableFuture<V> future = newCompletableFuture();
if (isDone()) {
unblockWhenComplete(action, executor, future);
} else {
Object result = registerWaiter(new WhenCompleteNode(future, action), executor);
if (result != UNRESOLVED) {
unblockWhenComplete(action, executor, future);
}
}
return future;
}
@Override
public <U> InternalCompletableFuture<U> thenCompose(@Nonnull Function<? super V, ? extends CompletionStage<U>> fn) {
return thenComposeAsync(fn, defaultExecutor());
}
@Override
public <U> InternalCompletableFuture<U> thenComposeAsync(@Nonnull Function<? super V, ? extends CompletionStage<U>> fn) {
return thenComposeAsync(fn, defaultExecutor());
}
@Override
public <U> InternalCompletableFuture<U> thenComposeAsync(@Nonnull Function<? super V, ? extends CompletionStage<U>> fn,
@Nonnull Executor executor) {
requireNonNull(fn);
requireNonNull(executor);
final InternalCompletableFuture<U> future = newCompletableFuture();
if (isDone()) {
unblockCompose(fn, executor, future);
} else {
Object result = registerWaiter(new ComposeNode<V, U>(future, fn), executor);
if (result != UNRESOLVED) {
unblockCompose(fn, executor, future);
}
}
return future;
}
@Override
public <U, R> InternalCompletableFuture<R> thenCombine(@Nonnull CompletionStage<? extends U> other,
@Nonnull BiFunction<? super V, ? super U, ? extends R> fn) {
return thenCombineAsync(other, fn, defaultExecutor());
}
@Override
public <U, R> InternalCompletableFuture<R> thenCombineAsync(@Nonnull CompletionStage<? extends U> other,
@Nonnull BiFunction<? super V, ? super U, ? extends R> fn) {
return thenCombineAsync(other, fn, defaultExecutor());
}
@Override
public <U, R> InternalCompletableFuture<R> thenCombineAsync(@Nonnull CompletionStage<? extends U> other,
@Nonnull BiFunction<? super V, ? super U, ? extends R> fn,
@Nonnull Executor executor) {
requireNonNull(other);
requireNonNull(fn);
requireNonNull(executor);
final InternalCompletableFuture<R> future = newCompletableFuture();
if (isDone()) {
unblockCombine(other, fn, executor, future);
} else {
Object result = registerWaiter(new CombineNode<V, U, R>(future, other.toCompletableFuture(), fn), executor);
if (result != UNRESOLVED) {
unblockCombine(other, fn, executor, future);
}
}
return future;
}
@Override
public <U> InternalCompletableFuture<Void> thenAcceptBoth(@Nonnull CompletionStage<? extends U> other,
@Nonnull BiConsumer<? super V, ? super U> action) {
return thenAcceptBothAsync(other, action, defaultExecutor());
}
@Override
public <U> InternalCompletableFuture<Void> thenAcceptBothAsync(@Nonnull CompletionStage<? extends U> other,
@Nonnull BiConsumer<? super V, ? super U> action) {
return thenAcceptBothAsync(other, action, defaultExecutor());
}
@Override
public <U> InternalCompletableFuture<Void> thenAcceptBothAsync(@Nonnull CompletionStage<? extends U> other,
@Nonnull BiConsumer<? super V, ? super U> action,
@Nonnull Executor executor) {
requireNonNull(action);
requireNonNull(executor);
final InternalCompletableFuture<Void> future = newCompletableFuture();
final CompletableFuture<? extends U> otherFuture =
(other instanceof CompletableFuture) ? (CompletableFuture<? extends U>) other : other.toCompletableFuture();
if (isDone()) {
unblockAcceptBoth(otherFuture, action, executor, future);
} else {
Object result = registerWaiter(new AcceptBothNode<>(future, otherFuture, action), executor);
if (result != UNRESOLVED) {
unblockAcceptBoth(otherFuture, action, executor, future);
}
}
return future;
}
@Override
public InternalCompletableFuture<Void> runAfterBoth(@Nonnull CompletionStage<?> other, @Nonnull Runnable action) {
return runAfterBothAsync(other, action, defaultExecutor());
}
@Override
public InternalCompletableFuture<Void> runAfterBothAsync(@Nonnull CompletionStage<?> other, @Nonnull Runnable action) {
return runAfterBothAsync(other, action, defaultExecutor());
}
@Override
public InternalCompletableFuture<Void> runAfterBothAsync(@Nonnull CompletionStage<?> other,
@Nonnull Runnable action,
@Nonnull Executor executor) {
requireNonNull(other);
requireNonNull(action);
requireNonNull(executor);
final InternalCompletableFuture<Void> future = newCompletableFuture();
final CompletableFuture<?> otherFuture =
(other instanceof CompletableFuture) ? (CompletableFuture<?>) other : other.toCompletableFuture();
if (isDone()) {
unblockRunAfterBoth(otherFuture, action, executor, future);
} else {
Object result = registerWaiter(new RunAfterBothNode<>(future, otherFuture, action), executor);
if (result != UNRESOLVED) {
unblockRunAfterBoth(otherFuture, action, executor, future);
}
}
return future;
}
@Override
public <U> InternalCompletableFuture<U> applyToEither(@Nonnull CompletionStage<? extends V> other,
@Nonnull Function<? super V, U> fn) {
return applyToEitherAsync(other, fn, defaultExecutor());
}
@Override
public <U> InternalCompletableFuture<U> applyToEitherAsync(@Nonnull CompletionStage<? extends V> other,
@Nonnull Function<? super V, U> fn) {
return applyToEitherAsync(other, fn, defaultExecutor());
}
@Override
public <U> InternalCompletableFuture<U> applyToEitherAsync(@Nonnull CompletionStage<? extends V> other,
@Nonnull Function<? super V, U> fn,
@Nonnull Executor executor) {
requireNonNull(other);
requireNonNull(fn);
requireNonNull(executor);
final InternalCompletableFuture<U> future = newCompletableFuture();
final CompletableFuture<? extends V> otherFuture =
(other instanceof CompletableFuture) ? (CompletableFuture<? extends V>) other : other.toCompletableFuture();
if (isDone()) {
unblockApplyToEither(fn, executor, future);
} else {
ApplyEither<? super V, U> waiter = new ApplyEither<>(future, fn);
Object result = registerWaiter(waiter, executor);
if (result == UNRESOLVED) {
otherFuture.whenCompleteAsync(waiter, executor);
return future;
} else {
unblockApplyToEither(fn, executor, future);
}
}
return future;
}
@Override
public InternalCompletableFuture<Void> acceptEither(@Nonnull CompletionStage<? extends V> other,
@Nonnull Consumer<? super V> action) {
return acceptEitherAsync(other, action, defaultExecutor());
}
@Override
public InternalCompletableFuture<Void> acceptEitherAsync(@Nonnull CompletionStage<? extends V> other,
@Nonnull Consumer<? super V> action) {
return acceptEitherAsync(other, action, defaultExecutor());
}
@Override
public InternalCompletableFuture<Void> acceptEitherAsync(@Nonnull CompletionStage<? extends V> other,
@Nonnull Consumer<? super V> action,
@Nonnull Executor executor) {
requireNonNull(other);
requireNonNull(action);
requireNonNull(executor);
final InternalCompletableFuture<Void> future = newCompletableFuture();
final CompletableFuture<? extends V> otherFuture =
(other instanceof CompletableFuture) ? (CompletableFuture<? extends V>) other : other.toCompletableFuture();
if (isDone()) {
unblockAcceptEither(action, executor, future);
} else {
AcceptEither<? super V> waiter = new AcceptEither<>(future, action);
Object result = registerWaiter(waiter, executor);
if (result == UNRESOLVED) {
otherFuture.whenCompleteAsync(waiter, executor);
return future;
} else {
unblockAcceptEither(action, executor, future);
}
}
return future;
}
@Override
public InternalCompletableFuture<Void> runAfterEither(CompletionStage<?> other, Runnable action) {
return runAfterEitherAsync(other, action, defaultExecutor());
}
@Override
public InternalCompletableFuture<Void> runAfterEitherAsync(@Nonnull CompletionStage<?> other, @Nonnull Runnable action) {
return runAfterEitherAsync(other, action, defaultExecutor());
}
@Override
public InternalCompletableFuture<Void> runAfterEitherAsync(@Nonnull CompletionStage<?> other,
@Nonnull Runnable action,
@Nonnull Executor executor) {
requireNonNull(other);
requireNonNull(action);
requireNonNull(executor);
final InternalCompletableFuture<Void> future = newCompletableFuture();
final CompletableFuture<?> otherFuture =
(other instanceof CompletableFuture) ? (CompletableFuture<?>) other : other.toCompletableFuture();
if (isDone()) {
unblockRunAfterEither(action, executor, future);
} else {
RunAfterEither waiter = new RunAfterEither(future, action);
Object result = registerWaiter(waiter, executor);
if (result == UNRESOLVED) {
otherFuture.whenCompleteAsync(waiter, executor);
return future;
} else {
unblockRunAfterEither(action, executor, future);
}
}
return future;
}
@Override
public InternalCompletableFuture<V> toCompletableFuture() {
return this;
}
boolean compareAndSetState(Object oldState, Object newState) {
return STATE_UPDATER.compareAndSet(this, oldState, newState);
}
protected final Object getState() {
return state;
}
@Override
public final boolean isDone() {
return isDone(state);
}
protected void onInterruptDetected() {
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return completeExceptionally(new CancellationException());
}
@Override
public boolean isCancelled() {
return isStateCancelled(state);
}
@Override
public boolean isCompletedExceptionally() {
return (state instanceof ExceptionalResult);
}
@Override
public final V join() {
final Object response = registerWaiter(Thread.currentThread(), null);
if (response != UNRESOLVED) {
return resolveAndThrowWithJoinConvention(response);
}
boolean interrupted = false;
try {
for (; ; ) {
park();
if (isDone()) {
return resolveAndThrowWithJoinConvention(state);
} else if (Thread.interrupted()) {
interrupted = true;
onInterruptDetected();
}
}
} finally {
restoreInterrupt(interrupted);
}
}
/**
* Similarly to {@link #join()}, returns the value when complete or throws an unchecked exception if
* completed exceptionally. Unlike {@link #join()}, checked exceptions are not wrapped in {@link CompletionException};
* rather they are wrapped in {@link com.hazelcast.core.HazelcastException}s.
*
* @return the result
*/
@Override
public V joinInternal() {
final Object response = registerWaiter(Thread.currentThread(), null);
if (response != UNRESOLVED) {
// no registration was done since a value is available.
return resolveAndThrowForJoinInternal(response);
}
boolean interrupted = false;
try {
for (; ; ) {
park();
if (isDone()) {
return resolveAndThrowForJoinInternal(state);
} else if (Thread.interrupted()) {
interrupted = true;
onInterruptDetected();
}
}
} finally {
restoreInterrupt(interrupted);
}
}
V resolveAndThrowForJoinInternal(Object unresolved) {
Object resolved = resolve(unresolved);
if (!(resolved instanceof ExceptionalResult)) {
return (V) resolved;
} else {
throw sneakyThrow(((ExceptionalResult) resolved).wrapForJoinInternal());
}
}
@Override
public final V get() throws InterruptedException, ExecutionException {
Object response = registerWaiter(Thread.currentThread(), null);
if (response != UNRESOLVED) {
// no registration was done since a value is available.
return resolveAndThrowIfException(response);
}
boolean interrupted = false;
try {
for (; ; ) {
park();
if (isDone()) {
return resolveAndThrowIfException(state);
} else if (Thread.interrupted()) {
interrupted = true;
onInterruptDetected();
}
}
} finally {
restoreInterrupt(interrupted);
}
}
@Override
public final V get(final long timeout, final TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
Object response = registerWaiter(Thread.currentThread(), null);
if (response != UNRESOLVED) {
return resolveAndThrowIfException(response);
}
long deadlineNanos = System.nanoTime() + unit.toNanos(timeout);
boolean interrupted = false;
try {
long timeoutNanos = unit.toNanos(timeout);
while (timeoutNanos > 0) {
parkNanos(timeoutNanos);
timeoutNanos = deadlineNanos - System.nanoTime();
if (isDone()) {
return resolveAndThrowIfException(state);
} else if (Thread.interrupted()) {
interrupted = true;
onInterruptDetected();
}
}
} finally {
restoreInterrupt(interrupted);
}
unregisterWaiter(Thread.currentThread());
throw newTimeoutException(timeout, unit);
}
@Override
public V getNow(V valueIfAbsent) {
return isDone() ? join() : valueIfAbsent;
}
@Override
public boolean completeExceptionally(Throwable ex) {
return completeExceptionallyInternal(ex);
}
@Override
public void obtrudeValue(V value) {
obtrude0(value);
}
@Override
public void obtrudeException(Throwable ex) {
obtrude0(wrapThrowable(ex));
}
private void obtrude0(Object value) {
for (; ; ) {
final Object oldState = state;
if (compareAndSetState(oldState, value)) {
onComplete();
unblockAll(oldState, defaultExecutor());
break;
}
}
}
@Override
public int getNumberOfDependents() {
int dependents = 0;
Object index = state;
while (index instanceof WaitNode) {
dependents++;
index = ((WaitNode) index).next;
}
if (index instanceof Waiter) {
// the first dependent registered with a default executor
// is not wrapped in a WaitNode
dependents++;
}
return dependents;
}
private void unblockAll(Object waiter, Executor executor) {
while (waiter != null) {
if (waiter instanceof Thread) {
unpark((Thread) waiter);
return;
} else if (waiter.getClass() == WaitNode.class) {
WaitNode waitNode = (WaitNode) waiter;
unblockAll(waitNode.waiter, waitNode.executor);
waiter = waitNode.next;
} else {
unblockOtherNode(waiter, executor);
return;
}
}
}
private void unblockAccept(@Nonnull final Consumer<? super V> consumer,
@Nonnull Executor executor,
@Nonnull InternalCompletableFuture<Void> future) {
final Object value = resolve(state);
if (cascadeException(value, future)) {
return;
}
try {
executor.execute(() -> {
try {
consumer.accept((V) value);
future.complete(null);
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
} catch (RejectedExecutionException e) {
future.completeExceptionally(wrapToInstanceNotActiveException(e));
}
}
/**
*
* @param waiter the current wait node, see javadoc of {@link #state state field}
* @param executor the {@link Executor} on which to execute the action associated with {@code waiter}
*/
@SuppressWarnings("checkstyle:CyclomaticComplexity")
protected void unblockOtherNode(Object waiter, Executor executor) {
if (!(waiter instanceof Waiter)) {
return;
}
Object value = resolve(state);
if (waiter instanceof UniWaiter) {
((UniWaiter) waiter).execute(executor, value);
} else if (waiter instanceof BiWaiter) {
Throwable t = (value instanceof ExceptionalResult) ? ((ExceptionalResult) value).cause : null;
value = (value instanceof ExceptionalResult) ? null : value;
((BiWaiter) waiter).execute(executor, value, t);
} else if (waiter instanceof ExceptionallyNode) {
((ExceptionallyNode) waiter).execute(value);
}
}
protected abstract Exception wrapToInstanceNotActiveException(RejectedExecutionException e);
protected V returnOrThrowWithJoinConventions(Object resolved) {
if (!(resolved instanceof ExceptionalResult)) {
return (V) resolved;
}
Throwable cause = ((ExceptionalResult) resolved).cause;
if (cause instanceof CancellationException) {
throw (CancellationException) cause;
} else if (cause instanceof CompletionException) {
throw (CompletionException) cause;
}
throw new CompletionException(cause);
}
/**
* @param value the resolved state of this future
* @return an {@link ExceptionalResult} wrapping a {@link Throwable} in case value is resolved
* to an exception, or the normal completion value. Subclasses may choose to treat
* specific normal completion values in a special way (eg deserialize when the completion
* value is an instance of {@code Data}.
*/
protected Object resolve(Object value) {
return value;
}
protected V resolveAndThrowWithJoinConvention(Object state) {
Object value = resolve(state);
return returnOrThrowWithJoinConventions(value);
}
protected <U> void unblockApply(@Nonnull final Function<? super V, ? extends U> function,
@Nonnull Executor executor,
@Nonnull InternalCompletableFuture<U> future) {
final Object value = resolve(state);
if (cascadeException(value, future)) {
return;
}
try {
executor.execute(() -> {
try {
U result = function.apply((V) value);
future.complete(result);
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
} catch (RejectedExecutionException e) {
future.completeExceptionally(wrapToInstanceNotActiveException(e));
}
}
protected void unblockRun(@Nonnull final Runnable runnable,
@Nonnull Executor executor,
@Nonnull CompletableFuture<Void> future) {
final Object value = resolve(state);
if (cascadeException(value, future)) {
return;
}
runAfter0(future, runnable, executor);
}
protected <U> void unblockHandle(@Nonnull BiFunction<? super V, Throwable, ? extends U> fn,
@Nonnull Executor executor,
@Nonnull CompletableFuture<U> future) {
final Object result = resolve(state);
V value;
Throwable throwable;
if (result instanceof ExceptionalResult) {
throwable = ((ExceptionalResult) result).getCause();
value = null;
} else {
throwable = null;
value = (V) result;
}
try {
executor.execute(() -> {
try {
U r = fn.apply(value, throwable);
future.complete(r);
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
} catch (RejectedExecutionException e) {
future.completeExceptionally(wrapToInstanceNotActiveException(e));
}
}
protected void unblockWhenComplete(@Nonnull final BiConsumer<? super V, ? super Throwable> biConsumer,
@Nonnull Executor executor,
@Nonnull CompletableFuture<V> future) {
Object result = resolve(state);
V value;
Throwable throwable;
if (result instanceof ExceptionalResult) {
throwable = ((ExceptionalResult) result).cause;
value = null;
} else {
throwable = null;
value = (V) result;
}
try {
executor.execute(() -> {
try {
biConsumer.accept((V) value, throwable);
} catch (Throwable t) {
completeDependentExceptionally(future, throwable, t);
return;
}
completeDependent(future, value, throwable);
});
} catch (RejectedExecutionException e) {
future.completeExceptionally(wrapToInstanceNotActiveException(e));
}
}
@Override
public InternalCompletableFuture<V> exceptionally(@Nonnull Function<Throwable, ? extends V> fn) {
requireNonNull(fn);
Object result = resolve(state);
final InternalCompletableFuture<V> future = newCompletableFuture();
for (; ; ) {
if (result != UNRESOLVED && isDone()) {
if (result instanceof ExceptionalResult) {
Throwable throwable = ((ExceptionalResult) result).cause;
try {
V value = fn.apply(throwable);
future.complete(value);
} catch (Throwable t) {
future.completeExceptionally(t);
}
} else {
future.complete((V) result);
}
return future;
} else {
result = registerWaiter(new ExceptionallyNode<>(future, fn), null);
if (result == UNRESOLVED) {
return future;
} else {
result = resolve(state);
}
}
}
}
protected <U> void unblockCompose(@Nonnull final Function<? super V, ? extends CompletionStage<U>> function,
@Nonnull Executor executor,
@Nonnull CompletableFuture<U> future) {
Object result = resolve(state);
if (cascadeException(result, future)) {
return;
}
final V res = (V) result;
try {
executor.execute(() -> {
try {
CompletionStage<U> r = function.apply(res);
r.whenComplete((v, t) -> {
if (t == null) {
future.complete(v);
} else {
future.completeExceptionally(t);
}
});
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
} catch (RejectedExecutionException e) {
future.completeExceptionally(wrapToInstanceNotActiveException(e));
}
}
@SuppressWarnings("checkstyle:npathcomplexity")
protected <U, R> void unblockCombine(@Nonnull CompletionStage<? extends U> other,
@Nonnull final BiFunction<? super V, ? super U, ? extends R> function,
@Nonnull Executor executor,
@Nonnull InternalCompletableFuture<R> future) {
Object result = resolve(state);
final CompletableFuture<? extends U> otherFuture =
(other instanceof CompletableFuture) ? (CompletableFuture<? extends U>) other : other.toCompletableFuture();
// CompletionStage#thenCombine specifies to wait both futures for normal completion,
// but does not specify that it is required to wait for both when completed exceptionally.
// The CompletableFuture#thenCombine implementation actually waits both future completion
// even when one of them is completed exceptionally.
// In case this future is completed exceptionally, the result is also exceptionally
// completed without checking whether otherFuture is completed or not
if (cascadeException(result, future)) {
return;
}
final V value = (V) result;
if (!otherFuture.isDone()) {
// register on other future as waiter and return
otherFuture.whenCompleteAsync((v, t) -> {
if (t != null) {
future.completeExceptionally(t);
}
try {
R r = function.apply(value, v);
future.complete(r);
} catch (Throwable e) {
future.completeExceptionally(e);
}
}, executor);
return;
}
// both futures are done
if (otherFuture.isCompletedExceptionally()) {
otherFuture.whenComplete((v, t) -> {
future.completeExceptionally(t);
});
return;
}
U otherValue = otherFuture.join();
try {
executor.execute(() -> {
try {
R r = function.apply(value, otherValue);
future.complete(r);
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
} catch (RejectedExecutionException e) {
future.completeExceptionally(wrapToInstanceNotActiveException(e));
}
}
@SuppressWarnings("checkstyle:npathcomplexity")
private <U> void unblockAcceptBoth(@Nonnull CompletableFuture<? extends U> otherFuture,
@Nonnull final BiConsumer<? super V, ? super U> action,
@Nonnull Executor executor,
@Nonnull InternalCompletableFuture<Void> future) {
final Object value = resolve(state);
// in case this future is completed exceptionally, the result is also exceptionally completed
// without checking whether otherFuture is completed or not
if (cascadeException(value, future)) {
return;
}
if (!otherFuture.isDone()) {
// register on other future as waiter and return
otherFuture.whenCompleteAsync((u, t) -> {
if (t != null) {
future.completeExceptionally(t);
}
try {
action.accept((V) value, u);