/
FuturesTest.java
2750 lines (2397 loc) · 96.4 KB
/
FuturesTest.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 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.Throwables.propagateIfInstanceOf;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.util.concurrent.Futures.allAsList;
import static com.google.common.util.concurrent.Futures.get;
import static com.google.common.util.concurrent.Futures.getUnchecked;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static com.google.common.util.concurrent.Futures.successfulAsList;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.easymock.EasyMock.expect;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.testing.ClassSanityTester;
import com.google.common.testing.TestLogHandler;
import com.google.common.util.concurrent.ForwardingFuture.SimpleForwardingFuture;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import java.io.IOException;
import java.util.Arrays;
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.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.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Unit tests for {@link Futures}.
*
* TODO: Add tests for other Futures methods
*
* @author Nishant Thakkar
*/
public class FuturesTest extends TestCase {
private static final Logger combinedFutureLogger = Logger.getLogger(
"com.google.common.util.concurrent.Futures$CollectionFuture");
private final TestLogHandler combinedFutureLogHandler = new TestLogHandler();
private static final String DATA1 = "data";
private static final String DATA2 = "more data";
private static final String DATA3 = "most data";
private IMocksControl mocksControl;
@Override protected void setUp() throws Exception {
super.setUp();
combinedFutureLogger.addHandler(combinedFutureLogHandler);
mocksControl = EasyMock.createControl();
}
@Override protected void tearDown() throws Exception {
/*
* Clear interrupt for future tests.
*
* (Ideally we would perform interrupts only in threads that we create, but
* it's hard to imagine that anything will break in practice.)
*/
Thread.interrupted();
combinedFutureLogger.removeHandler(combinedFutureLogHandler);
super.tearDown();
}
public void testImmediateFuture() throws Exception {
ListenableFuture<String> future = Futures.immediateFuture(DATA1);
// Verify that the proper object is returned without waiting
assertSame(DATA1, future.get(0L, TimeUnit.MILLISECONDS));
}
public void testMultipleImmediateFutures() throws Exception {
ListenableFuture<String> future1 = Futures.immediateFuture(DATA1);
ListenableFuture<String> future2 = Futures.immediateFuture(DATA2);
// Verify that the proper objects are returned without waiting
assertSame(DATA1, future1.get(0L, TimeUnit.MILLISECONDS));
assertSame(DATA2, future2.get(0L, TimeUnit.MILLISECONDS));
}
public void testImmediateFailedFuture() throws Exception {
Exception exception = new Exception();
ListenableFuture<String> future =
Futures.immediateFailedFuture(exception);
try {
future.get(0L, TimeUnit.MILLISECONDS);
fail("This call was supposed to throw an ExecutionException");
} catch (ExecutionException expected) {
// This is good and expected
assertSame(exception, expected.getCause());
}
}
public void testImmediateFailedFuture_cancellationException() throws Exception {
CancellationException exception = new CancellationException();
ListenableFuture<String> future =
Futures.immediateFailedFuture(exception);
try {
future.get(0L, TimeUnit.MILLISECONDS);
fail("This call was supposed to throw an ExecutionException");
} catch (ExecutionException expected) {
// This is good and expected
assertSame(exception, expected.getCause());
assertFalse(future.isCancelled());
}
}
public void testImmediateCancelledFuture() throws Exception {
ListenableFuture<String> future = CallerClass1.immediateCancelledFuture();
assertTrue(future.isCancelled());
try {
CallerClass2.get(future);
fail();
} catch (CancellationException e) {
// There should be two CancellationException chained together. The outer one should have the
// stack trace of where the get() call was made, and the inner should have the stack trace of
// where the immediateCancelledFuture() call was made.
List<StackTraceElement> stackTrace = ImmutableList.copyOf(e.getStackTrace());
assertFalse(Iterables.any(stackTrace, hasClassName(CallerClass1.class)));
assertTrue(Iterables.any(stackTrace, hasClassName(CallerClass2.class)));
assertTrue(e.getCause() instanceof CancellationException);
stackTrace = ImmutableList.copyOf(e.getCause().getStackTrace());
assertTrue(Iterables.any(stackTrace, hasClassName(CallerClass1.class)));
assertFalse(Iterables.any(stackTrace, hasClassName(CallerClass2.class)));
}
}
private static Predicate<StackTraceElement> hasClassName(final Class<?> clazz) {
return new Predicate<StackTraceElement>() {
@Override
public boolean apply(StackTraceElement element) {
return element.getClassName().equals(clazz.getName());
}
};
}
private static final class CallerClass1 {
static ListenableFuture<String> immediateCancelledFuture() {
return Futures.immediateCancelledFuture();
}
}
private static final class CallerClass2 {
static <V> V get(ListenableFuture<V> future) throws ExecutionException, InterruptedException {
return future.get();
}
}
private static class MyException extends Exception {}
public void testImmediateCheckedFuture() throws Exception {
CheckedFuture<String, MyException> future = Futures.immediateCheckedFuture(
DATA1);
// Verify that the proper object is returned without waiting
assertSame(DATA1, future.get(0L, TimeUnit.MILLISECONDS));
assertSame(DATA1, future.checkedGet(0L, TimeUnit.MILLISECONDS));
}
public void testMultipleImmediateCheckedFutures() throws Exception {
CheckedFuture<String, MyException> future1 = Futures.immediateCheckedFuture(
DATA1);
CheckedFuture<String, MyException> future2 = Futures.immediateCheckedFuture(
DATA2);
// Verify that the proper objects are returned without waiting
assertSame(DATA1, future1.get(0L, TimeUnit.MILLISECONDS));
assertSame(DATA1, future1.checkedGet(0L, TimeUnit.MILLISECONDS));
assertSame(DATA2, future2.get(0L, TimeUnit.MILLISECONDS));
assertSame(DATA2, future2.checkedGet(0L, TimeUnit.MILLISECONDS));
}
public void testImmediateFailedCheckedFuture() throws Exception {
MyException exception = new MyException();
CheckedFuture<String, MyException> future =
Futures.immediateFailedCheckedFuture(exception);
try {
future.get(0L, TimeUnit.MILLISECONDS);
fail("This call was supposed to throw an ExecutionException");
} catch (ExecutionException expected) {
// This is good and expected
assertSame(exception, expected.getCause());
}
try {
future.checkedGet(0L, TimeUnit.MILLISECONDS);
fail("This call was supposed to throw an MyException");
} catch (MyException expected) {
// This is good and expected
assertSame(exception, expected);
}
}
// Class hierarchy for generics sanity checks
private static class Foo {}
private static class FooChild extends Foo {}
private static class Bar {}
private static class BarChild extends Bar {}
public void testTransform_genericsNull() throws Exception {
ListenableFuture<?> nullFuture = Futures.immediateFuture(null);
ListenableFuture<?> transformedFuture =
Futures.transform(nullFuture, Functions.constant(null));
assertNull(transformedFuture.get());
}
public void testTransform_genericsHierarchy() throws Exception {
ListenableFuture<FooChild> future = Futures.immediateFuture(null);
final BarChild barChild = new BarChild();
Function<Foo, BarChild> function = new Function<Foo, BarChild>() {
@Override public BarChild apply(Foo unused) {
return barChild;
}
};
Bar bar = Futures.transform(future, function).get();
assertSame(barChild, bar);
}
public void testTransform_cancelPropagatesToInput() throws Exception {
SettableFuture<Foo> input = SettableFuture.create();
AsyncFunction<Foo, Bar> function = new AsyncFunction<Foo, Bar>() {
@Override public ListenableFuture<Bar> apply(Foo unused) {
throw new AssertionFailedError("Unexpeted call to apply.");
}
};
assertTrue(Futures.transform(input, function).cancel(false));
assertTrue(input.isCancelled());
assertFalse(input.wasInterrupted());
}
public void testTransform_interruptPropagatesToInput() throws Exception {
SettableFuture<Foo> input = SettableFuture.create();
AsyncFunction<Foo, Bar> function = new AsyncFunction<Foo, Bar>() {
@Override public ListenableFuture<Bar> apply(Foo unused) {
throw new AssertionFailedError("Unexpeted call to apply.");
}
};
assertTrue(Futures.transform(input, function).cancel(true));
assertTrue(input.isCancelled());
assertTrue(input.wasInterrupted());
}
public void testTransform_cancelPropagatesToAsyncOutput() throws Exception {
ListenableFuture<Foo> immediate = Futures.immediateFuture(new Foo());
final SettableFuture<Bar> secondary = SettableFuture.create();
AsyncFunction<Foo, Bar> function = new AsyncFunction<Foo, Bar>() {
@Override public ListenableFuture<Bar> apply(Foo unused) {
return secondary;
}
};
assertTrue(Futures.transform(immediate, function).cancel(false));
assertTrue(secondary.isCancelled());
assertFalse(secondary.wasInterrupted());
}
public void testTransform_interruptPropagatesToAsyncOutput()
throws Exception {
ListenableFuture<Foo> immediate = Futures.immediateFuture(new Foo());
final SettableFuture<Bar> secondary = SettableFuture.create();
AsyncFunction<Foo, Bar> function = new AsyncFunction<Foo, Bar>() {
@Override public ListenableFuture<Bar> apply(Foo unused) {
return secondary;
}
};
assertTrue(Futures.transform(immediate, function).cancel(true));
assertTrue(secondary.isCancelled());
assertTrue(secondary.wasInterrupted());
}
public void testTransform_rejectionPropagatesToOutput()
throws Exception {
SettableFuture<Foo> input = SettableFuture.create();
ExecutorService executor = newDirectExecutorService();
ListenableFuture<String> transformed =
Futures.transform(input, Functions.toStringFunction(), executor);
executor.shutdown();
input.set(new Foo());
try {
transformed.get(5, TimeUnit.SECONDS);
fail();
} catch (ExecutionException expected) {
assertTrue(expected.getCause() instanceof RejectedExecutionException);
}
}
/**
* Tests that the function is invoked only once, even if it throws an
* exception.
*/
public void testTransformValueRemainsMemoized() throws Exception {
class Holder {
int value = 2;
}
final Holder holder = new Holder();
// This function adds the holder's value to the input value.
Function<Integer, Integer> adder = new Function<Integer, Integer>() {
@Override public Integer apply(Integer from) {
return from + holder.value;
}
};
// Since holder.value is 2, applying 4 should yield 6.
assertEquals(6, adder.apply(4).intValue());
ListenableFuture<Integer> immediateFuture = Futures.immediateFuture(4);
Future<Integer> transformedFuture = Futures.transform(immediateFuture, adder);
// The composed future also yields 6.
assertEquals(6, transformedFuture.get().intValue());
// Repeated calls yield the same value even though the function's behavior
// changes
holder.value = 3;
assertEquals(6, transformedFuture.get().intValue());
assertEquals(7, adder.apply(4).intValue());
// Once more, with feeling.
holder.value = 4;
assertEquals(6, transformedFuture.get().intValue());
assertEquals(8, adder.apply(4).intValue());
// Memoized get also retains the value.
assertEquals(6, transformedFuture.get(1000, TimeUnit.SECONDS).intValue());
// Unsurprisingly, recomposing the future will return an updated value.
assertEquals(8, Futures.transform(immediateFuture, adder).get().intValue());
// Repeating, with the timeout version
assertEquals(8, Futures.transform(immediateFuture, adder).get(
1000, TimeUnit.SECONDS).intValue());
}
static class MyError extends Error {}
static class MyRuntimeException extends RuntimeException {}
/**
* Test that the function is invoked only once, even if it throws an
* exception. Also, test that that function's result is wrapped in an
* ExecutionException.
*/
public void testTransformExceptionRemainsMemoized() throws Throwable {
// We need to test with two input futures since ExecutionList.execute
// doesn't catch Errors and we cannot depend on the order that our
// transformations run. (So it is possible that the Error being thrown
// could prevent our second transformations from running).
SettableFuture<Integer> exceptionInput = SettableFuture.create();
ListenableFuture<Integer> exceptionComposedFuture =
Futures.transform(exceptionInput, newOneTimeExceptionThrower());
exceptionInput.set(0);
runGetIdempotencyTest(exceptionComposedFuture, MyRuntimeException.class);
SettableFuture<Integer> errorInput = SettableFuture.create();
ListenableFuture<Integer> errorComposedFuture =
Futures.transform(errorInput, newOneTimeErrorThrower());
errorInput.set(0);
runGetIdempotencyTest(errorComposedFuture, MyError.class);
/*
* Try again when the input's value is already filled in, since the flow is
* slightly different in that case.
*/
exceptionComposedFuture =
Futures.transform(exceptionInput, newOneTimeExceptionThrower());
runGetIdempotencyTest(exceptionComposedFuture, MyRuntimeException.class);
runGetIdempotencyTest(Futures.transform(errorInput, newOneTimeErrorThrower()), MyError.class);
runGetIdempotencyTest(errorComposedFuture, MyError.class);
}
private static void runGetIdempotencyTest(Future<Integer> transformedFuture,
Class<? extends Throwable> expectedExceptionClass) throws Throwable {
for (int i = 0; i < 5; i++) {
try {
transformedFuture.get();
fail();
} catch (ExecutionException expected) {
if (!expectedExceptionClass.isInstance(expected.getCause())) {
throw expected.getCause();
}
}
}
}
private static Function<Integer, Integer> newOneTimeExceptionThrower() {
return new Function<Integer, Integer>() {
int calls = 0;
@Override public Integer apply(Integer from) {
if (++calls > 1) {
fail();
}
throw new MyRuntimeException();
}
};
}
private static Function<Integer, Integer> newOneTimeErrorThrower() {
return new Function<Integer, Integer>() {
int calls = 0;
@Override public Integer apply(Integer from) {
if (++calls > 1) {
fail();
}
throw new MyError();
}
};
}
// TODO(cpovirk): top-level class?
static class ExecutorSpy implements Executor {
Executor delegate;
boolean wasExecuted;
public ExecutorSpy(Executor delegate) {
this.delegate = delegate;
}
@Override public void execute(Runnable command) {
delegate.execute(command);
wasExecuted = true;
}
}
public void testTransform_Executor() throws Exception {
Object value = new Object();
ExecutorSpy spy = new ExecutorSpy(directExecutor());
assertFalse(spy.wasExecuted);
ListenableFuture<Object> future = Futures.transform(
Futures.immediateFuture(value),
Functions.identity(), spy);
assertSame(value, future.get());
assertTrue(spy.wasExecuted);
}
public void testLazyTransform() throws Exception {
FunctionSpy<Object, String> spy =
new FunctionSpy<Object, String>(Functions.constant("bar"));
Future<String> input = Futures.immediateFuture("foo");
Future<String> transformed = Futures.lazyTransform(input, spy);
assertEquals(0, spy.getApplyCount());
assertEquals("bar", transformed.get());
assertEquals(1, spy.getApplyCount());
assertEquals("bar", transformed.get());
assertEquals(2, spy.getApplyCount());
}
public void testLazyTransform_exception() throws Exception {
final RuntimeException exception = new RuntimeException("deliberate");
Function<Integer, String> function = new Function<Integer, String>() {
@Override public String apply(Integer input) {
throw exception;
}
};
Future<String> transformed = Futures.lazyTransform(Futures.immediateFuture(1), function);
try {
transformed.get();
fail();
} catch (ExecutionException expected) {
assertSame(exception, expected.getCause());
}
try {
transformed.get(1, TimeUnit.SECONDS);
fail();
} catch (ExecutionException expected) {
assertSame(exception, expected.getCause());
}
}
private static class FunctionSpy<I, O> implements Function<I, O> {
private int applyCount;
private final Function<I, O> delegate;
public FunctionSpy(Function<I, O> delegate) {
this.delegate = delegate;
}
@Override
public O apply(I input) {
applyCount++;
return delegate.apply(input);
}
public int getApplyCount() {
return applyCount;
}
}
@SuppressWarnings("unchecked")
public void testWithFallback_inputDoesNotRaiseException() throws Exception {
FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
ListenableFuture<Integer> originalFuture = Futures.immediateFuture(7);
mocksControl.replay();
ListenableFuture<Integer> faultToleranteFuture = Futures.withFallback(originalFuture, fallback);
assertEquals(7, faultToleranteFuture.get().intValue());
mocksControl.verify();
}
@SuppressWarnings("unchecked")
public void testWithFallback_inputRaisesException() throws Exception {
FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
RuntimeException raisedException = new RuntimeException();
expect(fallback.create(raisedException)).andReturn(Futures.immediateFuture(20));
ListenableFuture<Integer> failingFuture = Futures.immediateFailedFuture(raisedException);
mocksControl.replay();
ListenableFuture<Integer> faultToleranteFuture = Futures.withFallback(failingFuture, fallback);
assertEquals(20, faultToleranteFuture.get().intValue());
mocksControl.verify();
}
public void testWithFallback_fallbackGeneratesRuntimeException() throws Exception {
RuntimeException expectedException = new RuntimeException();
runExpectedExceptionFallbackTest(expectedException, false);
}
public void testWithFallback_fallbackGeneratesCheckedException() throws Exception {
Exception expectedException = new Exception() {};
runExpectedExceptionFallbackTest(expectedException, false);
}
@SuppressWarnings("unchecked")
public void testWithFallback_fallbackGeneratesError() throws Exception {
final Error error = new Error("deliberate");
FutureFallback<Integer> fallback = new FutureFallback<Integer>() {
@Override public ListenableFuture<Integer> create(Throwable t) throws Exception {
throw error;
}
};
ListenableFuture<Integer> failingFuture = Futures.immediateFailedFuture(new RuntimeException());
try {
Futures.withFallback(failingFuture, fallback).get();
fail("An Exception should have been thrown!");
} catch (ExecutionException expected) {
assertSame(error, expected.getCause());
}
}
public void testWithFallback_fallbackReturnsRuntimeException() throws Exception {
RuntimeException expectedException = new RuntimeException();
runExpectedExceptionFallbackTest(expectedException, true);
}
public void testWithFallback_fallbackReturnsCheckedException() throws Exception {
Exception expectedException = new Exception() {};
runExpectedExceptionFallbackTest(expectedException, true);
}
@SuppressWarnings("unchecked")
private void runExpectedExceptionFallbackTest(
Throwable expectedException, boolean wrapInFuture) throws Exception {
FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
RuntimeException raisedException = new RuntimeException();
if (!wrapInFuture) {
// Exception is thrown in the body of the "fallback" method.
expect(fallback.create(raisedException)).andThrow(expectedException);
} else {
// Exception is wrapped in a future and returned.
expect(fallback.create(raisedException)).andReturn(
Futures.<Integer>immediateFailedFuture(expectedException));
}
ListenableFuture<Integer> failingFuture = Futures.immediateFailedFuture(raisedException);
mocksControl.replay();
ListenableFuture<Integer> faultToleranteFuture = Futures.withFallback(failingFuture, fallback);
try {
faultToleranteFuture.get();
fail("An Exception should have been thrown!");
} catch (ExecutionException ee) {
assertSame(expectedException, ee.getCause());
}
mocksControl.verify();
}
public void testWithFallback_fallbackNotReady() throws Exception {
ListenableFuture<Integer> primary = immediateFailedFuture(new Exception());
final SettableFuture<Integer> secondary = SettableFuture.create();
FutureFallback<Integer> fallback = new FutureFallback<Integer>() {
@Override
public ListenableFuture<Integer> create(Throwable t) {
return secondary;
}
};
ListenableFuture<Integer> derived = Futures.withFallback(primary, fallback);
secondary.set(1);
assertEquals(1, (int) derived.get());
}
@SuppressWarnings("unchecked")
public void testWithFallback_resultInterruptedBeforeFallback() throws Exception {
SettableFuture<Integer> primary = SettableFuture.create();
FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
mocksControl.replay();
ListenableFuture<Integer> derived = Futures.withFallback(primary, fallback);
derived.cancel(true);
assertTrue(primary.isCancelled());
assertTrue(primary.wasInterrupted());
mocksControl.verify();
}
@SuppressWarnings("unchecked")
public void testWithFallback_resultCancelledBeforeFallback() throws Exception {
SettableFuture<Integer> primary = SettableFuture.create();
FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
mocksControl.replay();
ListenableFuture<Integer> derived = Futures.withFallback(primary, fallback);
derived.cancel(false);
assertTrue(primary.isCancelled());
assertFalse(primary.wasInterrupted());
mocksControl.verify();
}
@SuppressWarnings("unchecked")
public void testWithFallback_resultCancelledAfterFallback() throws Exception {
SettableFuture<Integer> secondary = SettableFuture.create();
FutureFallback<Integer> fallback = mocksControl.createMock(FutureFallback.class);
RuntimeException raisedException = new RuntimeException();
expect(fallback.create(raisedException)).andReturn(secondary);
ListenableFuture<Integer> failingFuture = Futures.immediateFailedFuture(raisedException);
mocksControl.replay();
ListenableFuture<Integer> derived = Futures.withFallback(failingFuture, fallback);
derived.cancel(false);
assertTrue(secondary.isCancelled());
assertFalse(secondary.wasInterrupted());
mocksControl.verify();
}
public void testWithFallback_nullInsteadOfFuture() throws Exception {
ListenableFuture<?> inputFuture = immediateFailedFuture(new Exception());
ListenableFuture<?> chainedFuture =
Futures.withFallback(inputFuture, new FutureFallback<Integer>() {
@Override public ListenableFuture<Integer> create(Throwable t) {
return null;
}
});
try {
chainedFuture.get();
fail();
} catch (ExecutionException expected) {
NullPointerException cause = (NullPointerException) expected.getCause();
assertThat(cause).hasMessage("FutureFallback.create returned null instead of a Future. "
+ "Did you mean to return immediateFuture(null)?");
}
}
public void testTransform_genericsWildcard_AsyncFunction() throws Exception {
ListenableFuture<?> nullFuture = immediateFuture(null);
ListenableFuture<?> chainedFuture =
Futures.transform(nullFuture, constantAsyncFunction(nullFuture));
assertNull(chainedFuture.get());
}
private static <I, O> AsyncFunction<I, O> constantAsyncFunction(
final ListenableFuture<O> output) {
return new AsyncFunction<I, O>() {
@Override
public ListenableFuture<O> apply(I input) {
return output;
}
};
}
public void testTransform_genericsHierarchy_AsyncFunction() throws Exception {
ListenableFuture<FooChild> future = Futures.immediateFuture(null);
final BarChild barChild = new BarChild();
AsyncFunction<Foo, BarChild> function =
new AsyncFunction<Foo, BarChild>() {
@Override public AbstractFuture<BarChild> apply(Foo unused) {
AbstractFuture<BarChild> future = new AbstractFuture<BarChild>() {};
future.set(barChild);
return future;
}
};
Bar bar = Futures.transform(future, function).get();
assertSame(barChild, bar);
}
public void testTransform_asyncFunction_timeout()
throws InterruptedException, ExecutionException {
AsyncFunction<String, Integer> function = constantAsyncFunction(Futures.immediateFuture(1));
ListenableFuture<Integer> future = Futures.transform(
SettableFuture.<String>create(), function);
try {
future.get(1, TimeUnit.MILLISECONDS);
fail();
} catch (TimeoutException expected) {}
}
public void testTransform_asyncFunction_error() throws InterruptedException {
final Error error = new Error("deliberate");
AsyncFunction<String, Integer> function = new AsyncFunction<String, Integer>() {
@Override public ListenableFuture<Integer> apply(String input) {
throw error;
}
};
SettableFuture<String> inputFuture = SettableFuture.create();
ListenableFuture<Integer> outputFuture = Futures.transform(inputFuture, function);
inputFuture.set("value");
try {
outputFuture.get();
fail("should have thrown error");
} catch (ExecutionException e) {
assertSame(error, e.getCause());
}
}
public void testTransform_asyncFunction_nullInsteadOfFuture() throws Exception {
ListenableFuture<?> inputFuture = immediateFuture("a");
ListenableFuture<?> chainedFuture =
Futures.transform(inputFuture, constantAsyncFunction(null));
try {
chainedFuture.get();
fail();
} catch (ExecutionException expected) {
NullPointerException cause = (NullPointerException) expected.getCause();
assertThat(cause).hasMessage("AsyncFunction.apply returned null instead of a Future. "
+ "Did you mean to return immediateFuture(null)?");
}
}
public void testTransform_asyncFunction_cancelledWhileApplyingFunction()
throws InterruptedException, ExecutionException {
final CountDownLatch inFunction = new CountDownLatch(1);
final CountDownLatch functionDone = new CountDownLatch(1);
final SettableFuture<Integer> resultFuture = SettableFuture.create();
AsyncFunction<String, Integer> function = new AsyncFunction<String, Integer>() {
@Override public ListenableFuture<Integer> apply(String input) throws Exception {
inFunction.countDown();
functionDone.await();
return resultFuture;
}
};
SettableFuture<String> inputFuture = SettableFuture.create();
ListenableFuture<Integer> future = Futures.transform(
inputFuture, function, Executors.newSingleThreadExecutor());
inputFuture.set("value");
inFunction.await();
future.cancel(false);
functionDone.countDown();
try {
future.get();
fail();
} catch (CancellationException expected) {}
try {
resultFuture.get();
fail();
} catch (CancellationException expected) {}
}
public void testDereference_genericsWildcard() throws Exception {
ListenableFuture<?> inner = Futures.immediateFuture(null);
ListenableFuture<ListenableFuture<?>> outer =
Futures.<ListenableFuture<?>>immediateFuture(inner);
ListenableFuture<?> dereferenced = Futures.dereference(outer);
assertNull(dereferenced.get());
}
public void testDereference_genericsHierarchy() throws Exception {
FooChild fooChild = new FooChild();
ListenableFuture<FooChild> inner = Futures.immediateFuture(fooChild);
ListenableFuture<ListenableFuture<FooChild>> outer = Futures.immediateFuture(inner);
ListenableFuture<Foo> dereferenced = Futures.<Foo>dereference(outer);
assertSame(fooChild, dereferenced.get());
}
public void testDereference_resultCancelsOuter() throws Exception {
ListenableFuture<ListenableFuture<Foo>> outer = SettableFuture.create();
ListenableFuture<Foo> dereferenced = Futures.dereference(outer);
dereferenced.cancel(true);
assertTrue(outer.isCancelled());
}
public void testDereference_resultCancelsInner() throws Exception {
ListenableFuture<Foo> inner = SettableFuture.create();
ListenableFuture<ListenableFuture<Foo>> outer = Futures.immediateFuture(inner);
ListenableFuture<Foo> dereferenced = Futures.dereference(outer);
dereferenced.cancel(true);
assertTrue(inner.isCancelled());
}
public void testDereference_outerCancelsResult() throws Exception {
ListenableFuture<ListenableFuture<Foo>> outer = SettableFuture.create();
ListenableFuture<Foo> dereferenced = Futures.dereference(outer);
outer.cancel(true);
assertTrue(dereferenced.isCancelled());
}
public void testDereference_innerCancelsResult() throws Exception {
ListenableFuture<Foo> inner = SettableFuture.create();
ListenableFuture<ListenableFuture<Foo>> outer = Futures.immediateFuture(inner);
ListenableFuture<Foo> dereferenced = Futures.dereference(outer);
inner.cancel(true);
assertTrue(dereferenced.isCancelled());
}
/**
* Runnable which can be called a single time, and only after
* {@link #expectCall} is called.
*/
// TODO(cpovirk): top-level class?
static class SingleCallListener implements Runnable {
private boolean expectCall = false;
private final CountDownLatch calledCountDown =
new CountDownLatch(1);
@Override public void run() {
assertTrue("Listener called before it was expected", expectCall);
assertFalse("Listener called more than once", wasCalled());
calledCountDown.countDown();
}
public void expectCall() {
assertFalse("expectCall is already true", expectCall);
expectCall = true;
}
public boolean wasCalled() {
return calledCountDown.getCount() == 0;
}
public void waitForCall() throws InterruptedException {
assertTrue("expectCall is false", expectCall);
calledCountDown.await();
}
}
public void testAllAsList() throws Exception {
// Create input and output
SettableFuture<String> future1 = SettableFuture.create();
SettableFuture<String> future2 = SettableFuture.create();
SettableFuture<String> future3 = SettableFuture.create();
@SuppressWarnings("unchecked") // array is never modified
ListenableFuture<List<String>> compound =
Futures.allAsList(future1, future2, future3);
// Attach a listener
SingleCallListener listener = new SingleCallListener();
compound.addListener(listener, directExecutor());
// Satisfy each input and check the output
assertFalse(compound.isDone());
future1.set(DATA1);
assertFalse(compound.isDone());
future2.set(DATA2);
assertFalse(compound.isDone());
listener.expectCall();
future3.set(DATA3);
assertTrue(compound.isDone());
assertTrue(listener.wasCalled());
List<String> results = compound.get();
assertThat(results).containsExactly(DATA1, DATA2, DATA3).inOrder();
}
public void testAllAsList_emptyList() throws Exception {
SingleCallListener listener = new SingleCallListener();
listener.expectCall();
List<ListenableFuture<String>> futures = ImmutableList.of();
ListenableFuture<List<String>> compound = Futures.allAsList(futures);
compound.addListener(listener, directExecutor());
assertTrue(compound.isDone());
assertTrue(compound.get().isEmpty());
assertTrue(listener.wasCalled());
}
public void testAllAsList_emptyArray() throws Exception {
SingleCallListener listener = new SingleCallListener();
listener.expectCall();
@SuppressWarnings("unchecked") // array is never modified
ListenableFuture<List<String>> compound = Futures.allAsList();
compound.addListener(listener, directExecutor());
assertTrue(compound.isDone());
assertTrue(compound.get().isEmpty());
assertTrue(listener.wasCalled());
}
public void testAllAsList_failure() throws Exception {
SingleCallListener listener = new SingleCallListener();
SettableFuture<String> future1 = SettableFuture.create();
SettableFuture<String> future2 = SettableFuture.create();
@SuppressWarnings("unchecked") // array is never modified
ListenableFuture<List<String>> compound =
Futures.allAsList(future1, future2);
compound.addListener(listener, directExecutor());
listener.expectCall();
Throwable exception = new Throwable("failed1");
future1.setException(exception);
assertTrue(compound.isDone());
assertTrue(listener.wasCalled());
future2.set("result2");
try {
compound.get();
fail("Expected exception not thrown");
} catch (ExecutionException e) {
assertSame(exception, e.getCause());
}
}
public void testAllAsList_singleFailure() throws Exception {
Throwable exception = new Throwable("failed");
ListenableFuture<String> future = Futures.immediateFailedFuture(exception);
ListenableFuture<List<String>> compound = Futures.allAsList(ImmutableList.of(future));
try {
compound.get();
fail("Expected exception not thrown");
} catch (ExecutionException e) {
assertSame(exception, e.getCause());
}
}
public void testAllAsList_immediateFailure() throws Exception {
Throwable exception = new Throwable("failed");
ListenableFuture<String> future1 = Futures.immediateFailedFuture(exception);
ListenableFuture<String> future2 = Futures.immediateFuture("results");
ListenableFuture<List<String>> compound = Futures.allAsList(ImmutableList.of(future1, future2));
try {
compound.get();
fail("Expected exception not thrown");
} catch (ExecutionException e) {
assertSame(exception, e.getCause());
}
}
public void testAllAsList_error() throws Exception {
Error error = new Error("deliberate");
SettableFuture<String> future1 = SettableFuture.create();
ListenableFuture<String> future2 = Futures.immediateFuture("results");
ListenableFuture<List<String>> compound = Futures.allAsList(ImmutableList.of(future1, future2));
future1.setException(error);
try {
compound.get();
fail("Expected error not set in compound future.");
} catch (ExecutionException ee) {
assertSame(error, ee.getCause());
}