/
AbstractFutureTest.java
1341 lines (1228 loc) · 46.8 KB
/
AbstractFutureTest.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) 2011 The Guava Authors
*
* 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.google.common.util.concurrent;
import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION;
import static com.google.common.base.StandardSystemProperty.OS_NAME;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static org.junit.Assert.assertThrows;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.collect.Iterables;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.internal.InternalFutureFailureAccess;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Tests for {@link AbstractFuture}.
*
* @author Brian Stoler
*/
public class AbstractFutureTest extends TestCase {
public void testSuccess() throws ExecutionException, InterruptedException {
final Object value = new Object();
assertSame(
value,
new AbstractFuture<Object>() {
{
set(value);
}
}.get());
}
public void testException() throws InterruptedException {
final Throwable failure = new Throwable();
AbstractFuture<String> future =
new AbstractFuture<String>() {
{
setException(failure);
}
};
ExecutionException ee1 = getExpectingExecutionException(future);
ExecutionException ee2 = getExpectingExecutionException(future);
// Ensure we get a unique execution exception on each get
assertNotSame(ee1, ee2);
assertThat(ee1).hasCauseThat().isSameInstanceAs(failure);
assertThat(ee2).hasCauseThat().isSameInstanceAs(failure);
checkStackTrace(ee1);
checkStackTrace(ee2);
}
public void testCancel_notDoneNoInterrupt() throws Exception {
InterruptibleFuture future = new InterruptibleFuture();
assertTrue(future.cancel(false));
assertTrue(future.isCancelled());
assertTrue(future.isDone());
assertFalse(future.wasInterrupted());
assertFalse(future.interruptTaskWasCalled);
CancellationException e = assertThrows(CancellationException.class, () -> future.get());
assertThat(e).hasCauseThat().isNull();
}
public void testCancel_notDoneInterrupt() throws Exception {
InterruptibleFuture future = new InterruptibleFuture();
assertTrue(future.cancel(true));
assertTrue(future.isCancelled());
assertTrue(future.isDone());
assertTrue(future.wasInterrupted());
assertTrue(future.interruptTaskWasCalled);
CancellationException e = assertThrows(CancellationException.class, () -> future.get());
assertThat(e).hasCauseThat().isNull();
}
public void testCancel_done() throws Exception {
AbstractFuture<String> future =
new AbstractFuture<String>() {
{
set("foo");
}
};
assertFalse(future.cancel(true));
assertFalse(future.isCancelled());
assertTrue(future.isDone());
}
public void testGetWithTimeoutDoneFuture() throws Exception {
AbstractFuture<String> future =
new AbstractFuture<String>() {
{
set("foo");
}
};
assertEquals("foo", future.get(0, TimeUnit.SECONDS));
}
public void testEvilFuture_setFuture() throws Exception {
final RuntimeException exception = new RuntimeException("you didn't say the magic word!");
AbstractFuture<String> evilFuture =
new AbstractFuture<String>() {
@Override
public void addListener(Runnable r, Executor e) {
throw exception;
}
};
AbstractFuture<String> normalFuture = new AbstractFuture<String>() {};
normalFuture.setFuture(evilFuture);
assertTrue(normalFuture.isDone());
ExecutionException e = assertThrows(ExecutionException.class, () -> normalFuture.get());
assertThat(e).hasCauseThat().isSameInstanceAs(exception);
}
public void testRemoveWaiter_interruption() throws Exception {
final AbstractFuture<String> future = new AbstractFuture<String>() {};
WaiterThread waiter1 = new WaiterThread(future);
waiter1.start();
waiter1.awaitWaiting();
WaiterThread waiter2 = new WaiterThread(future);
waiter2.start();
waiter2.awaitWaiting();
// The waiter queue should be waiter2->waiter1
// This should wake up waiter1 and cause the waiter1 node to be removed.
waiter1.interrupt();
waiter1.join();
waiter2.awaitWaiting(); // should still be blocked
LockSupport.unpark(waiter2); // spurious wakeup
waiter2.awaitWaiting(); // should eventually re-park
future.set(null);
waiter2.join();
}
public void testRemoveWaiter_polling() throws Exception {
final AbstractFuture<String> future = new AbstractFuture<String>() {};
WaiterThread waiter = new WaiterThread(future);
waiter.start();
waiter.awaitWaiting();
PollingThread poller = new PollingThread(future);
poller.start();
PollingThread poller2 = new PollingThread(future);
poller2.start();
PollingThread poller3 = new PollingThread(future);
poller3.start();
poller.awaitInLoop();
poller2.awaitInLoop();
poller3.awaitInLoop();
// The waiter queue should be {poller x 3}->waiter1
waiter.interrupt();
// This should wake up waiter1 and cause the waiter1 node to be removed.
waiter.join();
future.set(null);
poller.join();
}
public void testToString_allUnique() throws Exception {
// Two futures should not have the same toString, to avoid people asserting on it
assertThat(SettableFuture.create().toString()).isNotEqualTo(SettableFuture.create().toString());
}
public void testToString_oom() throws Exception {
SettableFuture<Object> future = SettableFuture.create();
future.set(
new Object() {
@Override
public String toString() {
throw new OutOfMemoryError();
}
@Override
public int hashCode() {
throw new OutOfMemoryError();
}
});
String unused = future.toString();
SettableFuture<Object> future2 = SettableFuture.create();
// A more organic OOM from a toString implementation
Object object =
new Object() {
@Override
public String toString() {
return new String(new char[50_000]);
}
};
List<Object> list = Collections.singletonList(object);
for (int i = 0; i < 10; i++) {
Object[] array = new Object[500];
Arrays.fill(array, list);
list = Arrays.asList(array);
}
future2.set(list);
unused = future.toString();
}
public void testToString_notDone() throws Exception {
AbstractFuture<Object> testFuture =
new AbstractFuture<Object>() {
@Override
public String pendingToString() {
return "cause=[Because this test isn't done]";
}
};
assertThat(testFuture.toString())
.matches(
"[^\\[]+\\[status=PENDING, info=\\[cause=\\[Because this test isn't done\\]\\]\\]");
TimeoutException e =
assertThrows(TimeoutException.class, () -> testFuture.get(1, TimeUnit.NANOSECONDS));
assertThat(e.getMessage()).contains("1 nanoseconds");
assertThat(e.getMessage()).contains("Because this test isn't done");
}
public void testToString_completesDuringToString() throws Exception {
AbstractFuture<Object> testFuture =
new AbstractFuture<Object>() {
@Override
public String pendingToString() {
// Complete ourselves during the toString calculation
this.set(true);
return "cause=[Because this test isn't done]";
}
};
assertThat(testFuture.toString())
.matches("[^\\[]+\\[status=SUCCESS, result=\\[java.lang.Boolean@\\w+\\]\\]");
}
/**
* This test attempts to cause a future to wait for longer than it was requested to from a timed
* get() call. As measurements of time are prone to flakiness, it tries to assert based on ranges
* derived from observing how much time actually passed for various operations.
*/
@SuppressWarnings({"DeprecatedThreadMethods", "ThreadPriorityCheck"})
@AndroidIncompatible // Thread.suspend
public void testToString_delayedTimeout() throws Exception {
Integer javaVersion = Ints.tryParse(JAVA_SPECIFICATION_VERSION.value());
// Parsing to an integer might fail because Java 8 returns "1.8" instead of "8."
// We can continue if it's 1.8, and we can continue if it's an integer in [9, 20).
if (javaVersion != null && javaVersion >= 20) {
// TODO(b/261217224): Make this test work under newer JDKs.
return;
}
TimedWaiterThread thread =
new TimedWaiterThread(new AbstractFuture<Object>() {}, 2, TimeUnit.SECONDS);
thread.start();
thread.awaitWaiting();
thread.suspend();
// Sleep for enough time to add 1500 milliseconds of overwait to the get() call.
long toWaitMillis = 3500 - TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - thread.startTime);
Thread.sleep(toWaitMillis);
thread.setPriority(Thread.MAX_PRIORITY);
thread.resume();
thread.join();
// It's possible to race and suspend the thread just before the park call actually takes effect,
// causing the thread to be suspended for 3.5 seconds, and then park itself for 2 seconds after
// being resumed. To avoid a flake in this scenario, calculate how long that thread actually
// waited and assert based on that time. Empirically, the race where the thread ends up waiting
// for 5.5 seconds happens about 2% of the time.
boolean longWait = TimeUnit.NANOSECONDS.toSeconds(thread.timeSpentBlocked) >= 5;
// Count how long it actually took to return; we'll accept any number between the expected delay
// and the approximate actual delay, to be robust to variance in thread scheduling.
char overWaitNanosFirstDigit =
Long.toString(
thread.timeSpentBlocked - TimeUnit.MILLISECONDS.toNanos(longWait ? 5000 : 3000))
.charAt(0);
if (overWaitNanosFirstDigit < '4') {
overWaitNanosFirstDigit = '9';
}
String nanosRegex = "[4-" + overWaitNanosFirstDigit + "][0-9]+";
assertWithMessage(
"Spent " + thread.timeSpentBlocked + " ns blocked; slept for " + toWaitMillis + " ms")
.that(thread.exception)
.hasMessageThat()
.matches(
"Waited 2 seconds \\(plus "
+ (longWait ? "3" : "1")
+ " seconds, "
+ nanosRegex
+ " nanoseconds delay\\).*");
}
public void testToString_completed() throws Exception {
AbstractFuture<Object> testFuture2 =
new AbstractFuture<Object>() {
@Override
public String pendingToString() {
return "cause=[Someday...]";
}
};
AbstractFuture<Object> testFuture3 = new AbstractFuture<Object>() {};
testFuture3.setFuture(testFuture2);
assertThat(testFuture3.toString())
.matches(
"[^\\[]+\\[status=PENDING, setFuture=\\[[^\\[]+\\[status=PENDING,"
+ " info=\\[cause=\\[Someday...]]]]]");
testFuture2.set("result string");
assertThat(testFuture3.toString())
.matches("[^\\[]+\\[status=SUCCESS, result=\\[java.lang.String@\\w+\\]\\]");
}
public void testToString_cancelled() throws Exception {
assertThat(Futures.immediateCancelledFuture().toString())
.matches("[^\\[]+\\[status=CANCELLED\\]");
}
public void testToString_failed() {
assertThat(Futures.immediateFailedFuture(new RuntimeException("foo")).toString())
.matches("[^\\[]+\\[status=FAILURE, cause=\\[java.lang.RuntimeException: foo\\]\\]");
}
public void testToString_misbehaving() throws Exception {
assertThat(
new AbstractFuture<Object>() {
@Override
public String pendingToString() {
throw new RuntimeException("I'm a misbehaving implementation");
}
}.toString())
.matches(
"[^\\[]+\\[status=PENDING, info=\\[Exception thrown from implementation: "
+ "class java.lang.RuntimeException\\]\\]");
}
public void testCompletionFinishesWithDone() {
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 50000; i++) {
final AbstractFuture<String> future = new AbstractFuture<String>() {};
final AtomicReference<String> errorMessage = Atomics.newReference();
executor.execute(
new Runnable() {
@Override
public void run() {
future.set("success");
if (!future.isDone()) {
errorMessage.set("Set call exited before future was complete.");
}
}
});
executor.execute(
new Runnable() {
@Override
public void run() {
future.setException(new IllegalArgumentException("failure"));
if (!future.isDone()) {
errorMessage.set("SetException call exited before future was complete.");
}
}
});
executor.execute(
new Runnable() {
@Override
public void run() {
future.cancel(true);
if (!future.isDone()) {
errorMessage.set("Cancel call exited before future was complete.");
}
}
});
try {
future.get();
} catch (Throwable t) {
// Ignore, we just wanted to block.
}
String error = errorMessage.get();
assertNull(error, error);
}
executor.shutdown();
}
/**
* He did the bash, he did the future bash The future bash, it was a concurrency smash He did the
* bash, it caught on in a flash He did the bash, he did the future bash
*/
public void testFutureBash() {
if (isWindows()) {
return; // TODO: b/136041958 - Running very slowly on Windows CI.
}
final CyclicBarrier barrier =
new CyclicBarrier(
6 // for the setter threads
+ 50 // for the listeners
+ 50 // for the blocking get threads,
+ 1); // for the main thread
final ExecutorService executor = Executors.newFixedThreadPool(barrier.getParties());
final AtomicReference<AbstractFuture<String>> currentFuture = Atomics.newReference();
final AtomicInteger numSuccessfulSetCalls = new AtomicInteger();
Callable<@Nullable Void> completeSuccessfullyRunnable =
new Callable<@Nullable Void>() {
@Override
public @Nullable Void call() {
if (currentFuture.get().set("set")) {
numSuccessfulSetCalls.incrementAndGet();
}
awaitUnchecked(barrier);
return null;
}
};
Callable<@Nullable Void> completeExceptionallyRunnable =
new Callable<@Nullable Void>() {
Exception failureCause = new Exception("setException");
@Override
public @Nullable Void call() {
if (currentFuture.get().setException(failureCause)) {
numSuccessfulSetCalls.incrementAndGet();
}
awaitUnchecked(barrier);
return null;
}
};
Callable<@Nullable Void> cancelRunnable =
new Callable<@Nullable Void>() {
@Override
public @Nullable Void call() {
if (currentFuture.get().cancel(true)) {
numSuccessfulSetCalls.incrementAndGet();
}
awaitUnchecked(barrier);
return null;
}
};
Callable<@Nullable Void> setFutureCompleteSuccessfullyRunnable =
new Callable<@Nullable Void>() {
ListenableFuture<String> future = Futures.immediateFuture("setFuture");
@Override
public @Nullable Void call() {
if (currentFuture.get().setFuture(future)) {
numSuccessfulSetCalls.incrementAndGet();
}
awaitUnchecked(barrier);
return null;
}
};
Callable<@Nullable Void> setFutureCompleteExceptionallyRunnable =
new Callable<@Nullable Void>() {
ListenableFuture<String> future =
Futures.immediateFailedFuture(new Exception("setFuture"));
@Override
public @Nullable Void call() {
if (currentFuture.get().setFuture(future)) {
numSuccessfulSetCalls.incrementAndGet();
}
awaitUnchecked(barrier);
return null;
}
};
Callable<@Nullable Void> setFutureCancelRunnable =
new Callable<@Nullable Void>() {
ListenableFuture<String> future = Futures.immediateCancelledFuture();
@Override
public @Nullable Void call() {
if (currentFuture.get().setFuture(future)) {
numSuccessfulSetCalls.incrementAndGet();
}
awaitUnchecked(barrier);
return null;
}
};
final Set<Object> finalResults = Collections.synchronizedSet(Sets.newIdentityHashSet());
Runnable collectResultsRunnable =
new Runnable() {
@Override
public void run() {
try {
String result = Uninterruptibles.getUninterruptibly(currentFuture.get());
finalResults.add(result);
} catch (ExecutionException e) {
finalResults.add(e.getCause());
} catch (CancellationException e) {
finalResults.add(CancellationException.class);
} finally {
awaitUnchecked(barrier);
}
}
};
Runnable collectResultsTimedGetRunnable =
new Runnable() {
@Override
public void run() {
Future<String> future = currentFuture.get();
while (true) {
try {
String result = Uninterruptibles.getUninterruptibly(future, 0, TimeUnit.SECONDS);
finalResults.add(result);
break;
} catch (ExecutionException e) {
finalResults.add(e.getCause());
break;
} catch (CancellationException e) {
finalResults.add(CancellationException.class);
break;
} catch (TimeoutException e) {
// loop
}
}
awaitUnchecked(barrier);
}
};
List<Callable<?>> allTasks = new ArrayList<>();
allTasks.add(completeSuccessfullyRunnable);
allTasks.add(completeExceptionallyRunnable);
allTasks.add(cancelRunnable);
allTasks.add(setFutureCompleteSuccessfullyRunnable);
allTasks.add(setFutureCompleteExceptionallyRunnable);
allTasks.add(setFutureCancelRunnable);
for (int k = 0; k < 50; k++) {
// For each listener we add a task that submits it to the executor directly for the blocking
// get use case and another task that adds it as a listener to the future to exercise both
// racing addListener calls and addListener calls completing after the future completes.
final Runnable listener =
k % 2 == 0 ? collectResultsRunnable : collectResultsTimedGetRunnable;
allTasks.add(Executors.callable(listener));
allTasks.add(
new Callable<@Nullable Void>() {
@Override
public @Nullable Void call() throws Exception {
currentFuture.get().addListener(listener, executor);
return null;
}
});
}
assertEquals(allTasks.size() + 1, barrier.getParties());
for (int i = 0; i < 1000; i++) {
Collections.shuffle(allTasks);
final AbstractFuture<String> future = new AbstractFuture<String>() {};
currentFuture.set(future);
for (Callable<?> task : allTasks) {
@SuppressWarnings("unused") // https://errorprone.info/bugpattern/FutureReturnValueIgnored
Future<?> possiblyIgnoredError = executor.submit(task);
}
awaitUnchecked(barrier);
assertThat(future.isDone()).isTrue();
// inspect state and ensure it is correct!
// asserts that all get calling threads received the same value
Object result = Iterables.getOnlyElement(finalResults);
if (result == CancellationException.class) {
assertTrue(future.isCancelled());
if (future.wasInterrupted()) {
// We were cancelled, it is possible that setFuture could have succeeded too.
assertThat(numSuccessfulSetCalls.get()).isIn(Range.closed(1, 2));
} else {
assertThat(numSuccessfulSetCalls.get()).isEqualTo(1);
}
} else {
assertThat(numSuccessfulSetCalls.get()).isEqualTo(1);
}
// reset for next iteration
numSuccessfulSetCalls.set(0);
finalResults.clear();
}
executor.shutdown();
}
// setFuture and cancel() interact in more complicated ways than the other setters.
public void testSetFutureCancelBash() {
if (isWindows()) {
return; // TODO: b/136041958 - Running very slowly on Windows CI.
}
final int size = 50;
final CyclicBarrier barrier =
new CyclicBarrier(
2 // for the setter threads
+ size // for the listeners
+ size // for the get threads,
+ 1); // for the main thread
final ExecutorService executor = Executors.newFixedThreadPool(barrier.getParties());
final AtomicReference<AbstractFuture<String>> currentFuture = Atomics.newReference();
final AtomicReference<AbstractFuture<String>> setFutureFuture = Atomics.newReference();
final AtomicBoolean setFutureSetSuccess = new AtomicBoolean();
final AtomicBoolean setFutureCompletionSuccess = new AtomicBoolean();
final AtomicBoolean cancellationSuccess = new AtomicBoolean();
Runnable cancelRunnable =
new Runnable() {
@Override
public void run() {
cancellationSuccess.set(currentFuture.get().cancel(true));
awaitUnchecked(barrier);
}
};
Runnable setFutureCompleteSuccessfullyRunnable =
new Runnable() {
@Override
public void run() {
AbstractFuture<String> future = setFutureFuture.get();
setFutureSetSuccess.set(currentFuture.get().setFuture(future));
setFutureCompletionSuccess.set(future.set("hello-async-world"));
awaitUnchecked(barrier);
}
};
final Set<Object> finalResults = Collections.synchronizedSet(Sets.newIdentityHashSet());
Runnable collectResultsRunnable =
new Runnable() {
@Override
public void run() {
try {
String result = Uninterruptibles.getUninterruptibly(currentFuture.get());
finalResults.add(result);
} catch (ExecutionException e) {
finalResults.add(e.getCause());
} catch (CancellationException e) {
finalResults.add(CancellationException.class);
} finally {
awaitUnchecked(barrier);
}
}
};
Runnable collectResultsTimedGetRunnable =
new Runnable() {
@Override
public void run() {
Future<String> future = currentFuture.get();
while (true) {
try {
String result = Uninterruptibles.getUninterruptibly(future, 0, TimeUnit.SECONDS);
finalResults.add(result);
break;
} catch (ExecutionException e) {
finalResults.add(e.getCause());
break;
} catch (CancellationException e) {
finalResults.add(CancellationException.class);
break;
} catch (TimeoutException e) {
// loop
}
}
awaitUnchecked(barrier);
}
};
List<Runnable> allTasks = new ArrayList<>();
allTasks.add(cancelRunnable);
allTasks.add(setFutureCompleteSuccessfullyRunnable);
for (int k = 0; k < size; k++) {
// For each listener we add a task that submits it to the executor directly for the blocking
// get use case and another task that adds it as a listener to the future to exercise both
// racing addListener calls and addListener calls completing after the future completes.
final Runnable listener =
k % 2 == 0 ? collectResultsRunnable : collectResultsTimedGetRunnable;
allTasks.add(listener);
allTasks.add(
new Runnable() {
@Override
public void run() {
currentFuture.get().addListener(listener, executor);
}
});
}
assertEquals(allTasks.size() + 1, barrier.getParties()); // sanity check
for (int i = 0; i < 1000; i++) {
Collections.shuffle(allTasks);
final AbstractFuture<String> future = new AbstractFuture<String>() {};
final AbstractFuture<String> setFuture = new AbstractFuture<String>() {};
currentFuture.set(future);
setFutureFuture.set(setFuture);
for (Runnable task : allTasks) {
executor.execute(task);
}
awaitUnchecked(barrier);
assertThat(future.isDone()).isTrue();
// inspect state and ensure it is correct!
// asserts that all get calling threads received the same value
Object result = Iterables.getOnlyElement(finalResults);
if (result == CancellationException.class) {
assertTrue(future.isCancelled());
assertTrue(cancellationSuccess.get());
// cancellation can interleave in 3 ways
// 1. prior to setFuture
// 2. after setFuture before set() on the future assigned
// 3. after setFuture and set() are called but before the listener completes.
if (!setFutureSetSuccess.get() || !setFutureCompletionSuccess.get()) {
// If setFuture fails or set on the future fails then it must be because that future was
// cancelled
assertTrue(setFuture.isCancelled());
assertTrue(setFuture.wasInterrupted()); // we only call cancel(true)
}
} else {
// set on the future completed
assertFalse(cancellationSuccess.get());
assertTrue(setFutureSetSuccess.get());
assertTrue(setFutureCompletionSuccess.get());
}
// reset for next iteration
setFutureSetSuccess.set(false);
setFutureCompletionSuccess.set(false);
cancellationSuccess.set(false);
finalResults.clear();
}
executor.shutdown();
}
// Test to ensure that when calling setFuture with a done future only setFuture or cancel can
// return true.
public void testSetFutureCancelBash_withDoneFuture() {
final CyclicBarrier barrier =
new CyclicBarrier(
2 // for the setter threads
+ 1 // for the blocking get thread,
+ 1); // for the main thread
final ExecutorService executor = Executors.newFixedThreadPool(barrier.getParties());
final AtomicReference<AbstractFuture<String>> currentFuture = Atomics.newReference();
final AtomicBoolean setFutureSuccess = new AtomicBoolean();
final AtomicBoolean cancellationSuccess = new AtomicBoolean();
Callable<@Nullable Void> cancelRunnable =
new Callable<@Nullable Void>() {
@Override
public @Nullable Void call() {
cancellationSuccess.set(currentFuture.get().cancel(true));
awaitUnchecked(barrier);
return null;
}
};
Callable<@Nullable Void> setFutureCompleteSuccessfullyRunnable =
new Callable<@Nullable Void>() {
final ListenableFuture<String> future = Futures.immediateFuture("hello");
@Override
public @Nullable Void call() {
setFutureSuccess.set(currentFuture.get().setFuture(future));
awaitUnchecked(barrier);
return null;
}
};
final Set<Object> finalResults = Collections.synchronizedSet(Sets.newIdentityHashSet());
final Runnable collectResultsRunnable =
new Runnable() {
@Override
public void run() {
try {
String result = Uninterruptibles.getUninterruptibly(currentFuture.get());
finalResults.add(result);
} catch (ExecutionException e) {
finalResults.add(e.getCause());
} catch (CancellationException e) {
finalResults.add(CancellationException.class);
} finally {
awaitUnchecked(barrier);
}
}
};
List<Callable<?>> allTasks = new ArrayList<>();
allTasks.add(cancelRunnable);
allTasks.add(setFutureCompleteSuccessfullyRunnable);
allTasks.add(Executors.callable(collectResultsRunnable));
assertEquals(allTasks.size() + 1, barrier.getParties()); // sanity check
for (int i = 0; i < 1000; i++) {
Collections.shuffle(allTasks);
final AbstractFuture<String> future = new AbstractFuture<String>() {};
currentFuture.set(future);
for (Callable<?> task : allTasks) {
@SuppressWarnings("unused") // https://errorprone.info/bugpattern/FutureReturnValueIgnored
Future<?> possiblyIgnoredError = executor.submit(task);
}
awaitUnchecked(barrier);
assertThat(future.isDone()).isTrue();
// inspect state and ensure it is correct!
// asserts that all get calling threads received the same value
Object result = Iterables.getOnlyElement(finalResults);
if (result == CancellationException.class) {
assertTrue(future.isCancelled());
assertTrue(cancellationSuccess.get());
assertFalse(setFutureSuccess.get());
} else {
assertTrue(setFutureSuccess.get());
assertFalse(cancellationSuccess.get());
}
// reset for next iteration
setFutureSuccess.set(false);
cancellationSuccess.set(false);
finalResults.clear();
}
executor.shutdown();
}
// In a previous implementation this would cause a stack overflow after ~2000 futures chained
// together. Now it should only be limited by available memory (and time)
public void testSetFuture_stackOverflow() {
SettableFuture<String> orig = SettableFuture.create();
SettableFuture<String> prev = orig;
for (int i = 0; i < 100000; i++) {
SettableFuture<String> curr = SettableFuture.create();
prev.setFuture(curr);
prev = curr;
}
// prev represents the 'innermost' future
prev.set("done");
assertTrue(orig.isDone());
}
// Verify that StackOverflowError in a long chain of SetFuture doesn't cause the entire toString
// call to fail
@J2ktIncompatible
@GwtIncompatible
@AndroidIncompatible
public void testSetFutureToString_stackOverflow() {
SettableFuture<String> orig = SettableFuture.create();
SettableFuture<String> prev = orig;
for (int i = 0; i < 100000; i++) {
SettableFuture<String> curr = SettableFuture.create();
prev.setFuture(curr);
prev = curr;
}
// orig represents the 'outermost' future
assertThat(orig.toString())
.contains("Exception thrown from implementation: class java.lang.StackOverflowError");
}
public void testSetFuture_misbehavingFutureThrows() throws Exception {
SettableFuture<String> future = SettableFuture.create();
ListenableFuture<String> badFuture =
new ListenableFuture<String>() {
@Override
public boolean cancel(boolean interrupt) {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public boolean isCancelled() {
return false; // BAD!!
}
@Override
public String get() {
throw new CancellationException(); // BAD!!
}
@Override
public String get(long time, TimeUnit unit) {
throw new CancellationException(); // BAD!!
}
@Override
public void addListener(Runnable runnable, Executor executor) {
executor.execute(runnable);
}
};
future.setFuture(badFuture);
ExecutionException expected = getExpectingExecutionException(future);
assertThat(expected).hasCauseThat().isInstanceOf(IllegalArgumentException.class);
assertThat(expected).hasCauseThat().hasMessageThat().contains(badFuture.toString());
}
public void testSetFuture_misbehavingFutureDoesNotThrow() throws Exception {
SettableFuture<String> future = SettableFuture.create();
ListenableFuture<String> badFuture =
new ListenableFuture<String>() {
@Override
public boolean cancel(boolean interrupt) {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public boolean isCancelled() {
return true; // BAD!!
}
@Override
public String get() {
return "foo"; // BAD!!
}
@Override
public String get(long time, TimeUnit unit) {
return "foo"; // BAD!!
}
@Override
public void addListener(Runnable runnable, Executor executor) {
executor.execute(runnable);
}
};
future.setFuture(badFuture);
assertThat(future.isCancelled()).isTrue();
}
public void testCancel_stackOverflow() {
SettableFuture<String> orig = SettableFuture.create();
SettableFuture<String> prev = orig;
for (int i = 0; i < 100000; i++) {
SettableFuture<String> curr = SettableFuture.create();
prev.setFuture(curr);
prev = curr;
}
// orig is the 'outermost future', this should propagate fully down the stack of futures.
orig.cancel(true);
assertTrue(orig.isCancelled());
assertTrue(prev.isCancelled());
assertTrue(prev.wasInterrupted());
}
public void testSetFutureSelf_cancel() {
SettableFuture<String> orig = SettableFuture.create();
orig.setFuture(orig);
orig.cancel(true);
assertTrue(orig.isCancelled());
}
public void testSetFutureSelf_toString() {
SettableFuture<String> orig = SettableFuture.create();
orig.setFuture(orig);
assertThat(orig.toString()).contains("[status=PENDING, setFuture=[this future]]");
}
public void testSetSelf_toString() {
SettableFuture<Object> orig = SettableFuture.create();
orig.set(orig);
assertThat(orig.toString()).contains("[status=SUCCESS, result=[this future]]");
}
public void testSetFutureSelf_toStringException() {
SettableFuture<String> orig = SettableFuture.create();
orig.setFuture(
new AbstractFuture<String>() {
@Override
public String toString() {
throw new NullPointerException();
}
});
assertThat(orig.toString())
.contains(
"[status=PENDING, setFuture=[Exception thrown from implementation: class"
+ " java.lang.NullPointerException]]");
}
public void testSetIndirectSelf_toString() {
final SettableFuture<Object> orig = SettableFuture.create();
// unlike the above this indirection defeats the trivial cycle detection and causes a SOE
orig.setFuture(
new ForwardingListenableFuture<Object>() {
@Override
protected ListenableFuture<Object> delegate() {
return orig;
}
});
assertThat(orig.toString())
.contains("Exception thrown from implementation: class java.lang.StackOverflowError");
}