/
Futures.java
1589 lines (1508 loc) · 73.4 KB
/
Futures.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) 2006 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.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.CollectionFuture.ListFuture;
import com.google.common.util.concurrent.ImmediateFuture.ImmediateCancelledFuture;
import com.google.common.util.concurrent.ImmediateFuture.ImmediateFailedCheckedFuture;
import com.google.common.util.concurrent.ImmediateFuture.ImmediateFailedFuture;
import com.google.common.util.concurrent.ImmediateFuture.ImmediateSuccessfulCheckedFuture;
import com.google.common.util.concurrent.ImmediateFuture.ImmediateSuccessfulFuture;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotCall;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Static utility methods pertaining to the {@link Future} interface.
*
* <p>Many of these methods use the {@link ListenableFuture} API; consult the Guava User Guide
* article on <a href="https://github.com/google/guava/wiki/ListenableFutureExplained">{@code
* ListenableFuture}</a>.
*
* <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of
* asynchronous operations. You can chain them together manually with calls to methods like {@link
* Futures#transform(ListenableFuture, Function, Executor) Futures.transform}, but you will often
* find it easier to use a framework. Frameworks automate the process, often adding features like
* monitoring, debugging, and cancellation. Examples of frameworks include:
*
* <ul>
* <li><a href="http://google.github.io/dagger/producers.html">Dagger Producers</a>
* </ul>
*
* <p>If you do chain your operations manually, you may want to use {@link FluentFuture}.
*
* @author Kevin Bourrillion
* @author Nishant Thakkar
* @author Sven Mawson
* @since 1.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class Futures extends GwtFuturesCatchingSpecialization {
// A note on memory visibility.
// Many of the utilities in this class (transform, withFallback, withTimeout, asList, combine)
// have two requirements that significantly complicate their design.
// 1. Cancellation should propagate from the returned future to the input future(s).
// 2. The returned futures shouldn't unnecessarily 'pin' their inputs after completion.
//
// A consequence of these requirements is that the delegate futures cannot be stored in
// final fields.
//
// For simplicity the rest of this description will discuss Futures.catching since it is the
// simplest instance, though very similar descriptions apply to many other classes in this file.
//
// In the constructor of AbstractCatchingFuture, the delegate future is assigned to a field
// 'inputFuture'. That field is non-final and non-volatile. There are 2 places where the
// 'inputFuture' field is read and where we will have to consider visibility of the write
// operation in the constructor.
//
// 1. In the listener that performs the callback. In this case it is fine since inputFuture is
// assigned prior to calling addListener, and addListener happens-before any invocation of the
// listener. Notably, this means that 'volatile' is unnecessary to make 'inputFuture' visible
// to the listener.
//
// 2. In done() where we may propagate cancellation to the input. In this case it is _not_ fine.
// There is currently nothing that enforces that the write to inputFuture in the constructor is
// visible to done(). This is because there is no happens before edge between the write and a
// (hypothetical) unsafe read by our caller. Note: adding 'volatile' does not fix this issue,
// it would just add an edge such that if done() observed non-null, then it would also
// definitely observe all earlier writes, but we still have no guarantee that done() would see
// the inital write (just stronger guarantees if it does).
//
// See: http://cs.oswego.edu/pipermail/concurrency-interest/2015-January/013800.html
// For a (long) discussion about this specific issue and the general futility of life.
//
// For the time being we are OK with the problem discussed above since it requires a caller to
// introduce a very specific kind of data-race. And given the other operations performed by these
// methods that involve volatile read/write operations, in practice there is no issue. Also, the
// way in such a visibility issue would surface is most likely as a failure of cancel() to
// propagate to the input. Cancellation propagation is fundamentally racy so this is fine.
//
// Future versions of the JMM may revise safe construction semantics in such a way that we can
// safely publish these objects and we won't need this whole discussion.
// TODO(user,lukes): consider adding volatile to all these fields since in current known JVMs
// that should resolve the issue. This comes at the cost of adding more write barriers to the
// implementations.
private Futures() {}
/**
* Creates a {@link CheckedFuture} out of a normal {@link ListenableFuture} and a {@link Function}
* that maps from {@link Exception} instances into the appropriate checked type.
*
* <p><b>Warning:</b> We recommend against using {@code CheckedFuture} in new projects. {@code
* CheckedFuture} is difficult to build libraries atop. {@code CheckedFuture} ports of methods
* like {@link Futures#transformAsync} have historically had bugs, and some of these bugs are
* necessary, unavoidable consequences of the {@code CheckedFuture} API. Additionally, {@code
* CheckedFuture} encourages users to take exceptions from one thread and rethrow them in another,
* producing confusing stack traces.
*
* <p>The given mapping function will be applied to an {@link InterruptedException}, a {@link
* CancellationException}, or an {@link ExecutionException}. See {@link Future#get()} for details
* on the exceptions thrown.
*
* @since 9.0 (source-compatible since 1.0)
* @deprecated {@link CheckedFuture} cannot properly support the chained operations that are the
* primary goal of {@link ListenableFuture}. {@code CheckedFuture} also encourages users to
* rethrow exceptions from one thread in another thread, producing misleading stack traces.
* Additionally, it has a surprising policy about which exceptions to map and which to leave
* untouched. Guava users who want a {@code CheckedFuture} can fork the classes for their own
* use, possibly specializing them to the particular exception type they use. We recommend
* that most people use {@code ListenableFuture} and perform any exception wrapping
* themselves. This method is scheduled for removal from Guava in July 2018.
*/
// TODO(b/72241575): Remove by 2018-07
@Deprecated
@GwtIncompatible // TODO
public static <V, X extends Exception> CheckedFuture<V, X> makeChecked(
ListenableFuture<V> future, Function<? super Exception, X> mapper) {
return new MappingCheckedFuture<>(checkNotNull(future), mapper);
}
/**
* Creates a {@code ListenableFuture} which has its value set immediately upon construction. The
* getters just return the value. This {@code Future} can't be canceled or timed out and its
* {@code isDone()} method always returns {@code true}.
*/
public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) {
if (value == null) {
// This cast is safe because null is assignable to V for all V (i.e. it is covariant)
@SuppressWarnings({"unchecked", "rawtypes"})
ListenableFuture<V> typedNull = (ListenableFuture) ImmediateSuccessfulFuture.NULL;
return typedNull;
}
return new ImmediateSuccessfulFuture<V>(value);
}
/**
* Returns a {@code CheckedFuture} which has its value set immediately upon construction.
*
* <p>The returned {@code Future} can't be cancelled, and its {@code isDone()} method always
* returns {@code true}. Calling {@code get()} or {@code checkedGet()} will immediately return the
* provided value.
*
* @deprecated {@link CheckedFuture} cannot properly support the chained operations that are the
* primary goal of {@link ListenableFuture}. {@code CheckedFuture} also encourages users to
* rethrow exceptions from one thread in another thread, producing misleading stack traces.
* Additionally, it has a surprising policy about which exceptions to map and which to leave
* untouched. Guava users who want a {@code CheckedFuture} can fork the classes for their own
* use, possibly specializing them to the particular exception type they use. We recommend
* that most people use {@code ListenableFuture} and perform any exception wrapping
* themselves. This method is scheduled for removal from Guava in July 2018.
*/
// TODO(b/72241893): Remove by 2018-07
@Deprecated
@GwtIncompatible // TODO
public static <V, X extends Exception> CheckedFuture<V, X> immediateCheckedFuture(
@Nullable V value) {
return new ImmediateSuccessfulCheckedFuture<>(value);
}
/**
* Returns a {@code ListenableFuture} which has an exception set immediately upon construction.
*
* <p>The returned {@code Future} can't be cancelled, and its {@code isDone()} method always
* returns {@code true}. Calling {@code get()} will immediately throw the provided {@code
* Throwable} wrapped in an {@code ExecutionException}.
*/
public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable) {
checkNotNull(throwable);
return new ImmediateFailedFuture<V>(throwable);
}
/**
* Creates a {@code ListenableFuture} which is cancelled immediately upon construction, so that
* {@code isCancelled()} always returns {@code true}.
*
* @since 14.0
*/
public static <V> ListenableFuture<V> immediateCancelledFuture() {
return new ImmediateCancelledFuture<V>();
}
/**
* Returns a {@code CheckedFuture} which has an exception set immediately upon construction.
*
* <p>The returned {@code Future} can't be cancelled, and its {@code isDone()} method always
* returns {@code true}. Calling {@code get()} will immediately throw the provided {@code
* Exception} wrapped in an {@code ExecutionException}, and calling {@code checkedGet()} will
* throw the provided exception itself.
*
* @deprecated {@link CheckedFuture} cannot properly support the chained operations that are the
* primary goal of {@link ListenableFuture}. {@code CheckedFuture} also encourages users to
* rethrow exceptions from one thread in another thread, producing misleading stack traces.
* Additionally, it has a surprising policy about which exceptions to map and which to leave
* untouched. Guava users who want a {@code CheckedFuture} can fork the classes for their own
* use, possibly specializing them to the particular exception type they use. We recommend
* that most people use {@code ListenableFuture} and perform any exception wrapping
* themselves. This method is scheduled for removal from Guava in July 2018.
*/
// TODO(b/72241500): Remove by 2018-07
@Deprecated
@GwtIncompatible // TODO
public static <V, X extends Exception> CheckedFuture<V, X> immediateFailedCheckedFuture(
X exception) {
checkNotNull(exception);
return new ImmediateFailedCheckedFuture<>(exception);
}
/**
* Executes {@code callable} on the specified {@code executor}, returning a {@code Future}.
*
* @throws RejectedExecutionException if the task cannot be scheduled for execution
* @since 23.0
*/
public static <O> ListenableFuture<O> submitAsync(AsyncCallable<O> callable, Executor executor) {
TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
executor.execute(task);
return task;
}
/**
* Schedules {@code callable} on the specified {@code executor}, returning a {@code Future}.
*
* @throws RejectedExecutionException if the task cannot be scheduled for execution
* @since 23.0
*/
@GwtIncompatible // java.util.concurrent.ScheduledExecutorService
public static <O> ListenableFuture<O> scheduleAsync(
AsyncCallable<O> callable,
long delay,
TimeUnit timeUnit,
ScheduledExecutorService executorService) {
TrustedListenableFutureTask<O> task = TrustedListenableFutureTask.create(callable);
final Future<?> scheduled = executorService.schedule(task, delay, timeUnit);
task.addListener(
new Runnable() {
@Override
public void run() {
// Don't want to interrupt twice
scheduled.cancel(false);
}
},
directExecutor());
return task;
}
/**
* Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
* primary input fails with the given {@code exceptionType}, from the result provided by the
* {@code fallback}. {@link Function#apply} is not invoked until the primary input has failed, so
* if the primary input succeeds, it is never invoked. If, during the invocation of {@code
* fallback}, an exception is thrown, this exception is used as the result of the output {@code
* Future}.
*
* <p>Usage example:
*
* <pre>{@code
* ListenableFuture<Integer> fetchCounterFuture = ...;
*
* // Falling back to a zero counter in case an exception happens when
* // processing the RPC to fetch counters.
* ListenableFuture<Integer> faultTolerantFuture = Futures.catching(
* fetchCounterFuture, FetchException.class, x -> 0);
* }</pre>
*
* <p>This overload, which does not accept an executor, uses {@code directExecutor}, a dangerous
* choice in some cases. See the discussion in the {@link ListenableFuture#addListener
* ListenableFuture.addListener} documentation. All its warnings about heavyweight listeners are
* also applicable to heavyweight functions passed to this method.
*
* @param input the primary input {@code Future}
* @param exceptionType the exception type that triggers use of {@code fallback}. The exception
* type is matched against the input's exception. "The input's exception" means the cause of
* the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
* different kind of exception, that exception itself. To avoid hiding bugs and other
* unrecoverable errors, callers should prefer more specific types, avoiding {@code
* Throwable.class} in particular.
* @param fallback the {@link Function} to be called if {@code input} fails with the expected
* exception type. The function's argument is the input's exception. "The input's exception"
* means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
* {@code get()} throws a different kind of exception, that exception itself.
* @since 19.0
* @deprecated Use {@linkplain #catching(ListenableFuture, Class, Function, Executor) the overload
* that requires an executor}. For identical behavior, pass {@link
* MoreExecutors#directExecutor}, but consider whether another executor would be safer, as
* discussed in the {@link ListenableFuture#addListener ListenableFuture.addListener}
* documentation. This method is scheduled to be removed in July 2018.
*/
@Deprecated
@DoNotCall
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
public static <V, X extends Throwable> ListenableFuture<V> catching(
ListenableFuture<? extends V> input,
Class<X> exceptionType,
Function<? super X, ? extends V> fallback) {
return AbstractCatchingFuture.create(input, exceptionType, fallback, directExecutor());
}
/**
* Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
* primary input fails with the given {@code exceptionType}, from the result provided by the
* {@code fallback}. {@link Function#apply} is not invoked until the primary input has failed, so
* if the primary input succeeds, it is never invoked. If, during the invocation of {@code
* fallback}, an exception is thrown, this exception is used as the result of the output {@code
* Future}.
*
* <p>Usage example:
*
* <pre>{@code
* ListenableFuture<Integer> fetchCounterFuture = ...;
*
* // Falling back to a zero counter in case an exception happens when
* // processing the RPC to fetch counters.
* ListenableFuture<Integer> faultTolerantFuture = Futures.catching(
* fetchCounterFuture, FetchException.class, x -> 0, directExecutor());
* }</pre>
*
* <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
* the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
* documentation. All its warnings about heavyweight listeners are also applicable to heavyweight
* functions passed to this method.
*
* @param input the primary input {@code Future}
* @param exceptionType the exception type that triggers use of {@code fallback}. The exception
* type is matched against the input's exception. "The input's exception" means the cause of
* the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
* different kind of exception, that exception itself. To avoid hiding bugs and other
* unrecoverable errors, callers should prefer more specific types, avoiding {@code
* Throwable.class} in particular.
* @param fallback the {@link Function} to be called if {@code input} fails with the expected
* exception type. The function's argument is the input's exception. "The input's exception"
* means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
* {@code get()} throws a different kind of exception, that exception itself.
* @param executor the executor that runs {@code fallback} if {@code input} fails
* @since 19.0
*/
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
public static <V, X extends Throwable> ListenableFuture<V> catching(
ListenableFuture<? extends V> input,
Class<X> exceptionType,
Function<? super X, ? extends V> fallback,
Executor executor) {
return AbstractCatchingFuture.create(input, exceptionType, fallback, executor);
}
/**
* Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
* primary input fails with the given {@code exceptionType}, from the result provided by the
* {@code fallback}. {@link AsyncFunction#apply} is not invoked until the primary input has
* failed, so if the primary input succeeds, it is never invoked. If, during the invocation of
* {@code fallback}, an exception is thrown, this exception is used as the result of the output
* {@code Future}.
*
* <p>Usage examples:
*
* <pre>{@code
* ListenableFuture<Integer> fetchCounterFuture = ...;
*
* // Falling back to a zero counter in case an exception happens when
* // processing the RPC to fetch counters.
* ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
* fetchCounterFuture, FetchException.class, x -> immediateFuture(0));
* }</pre>
*
* <p>The fallback can also choose to propagate the original exception when desired:
*
* <pre>{@code
* ListenableFuture<Integer> fetchCounterFuture = ...;
*
* // Falling back to a zero counter only in case the exception was a
* // TimeoutException.
* ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
* fetchCounterFuture,
* FetchException.class,
* e -> {
* if (omitDataOnFetchFailure) {
* return immediateFuture(0);
* }
* throw e;
* });
* }</pre>
*
* <p>This overload, which does not accept an executor, uses {@code directExecutor}, a dangerous
* choice in some cases. See the discussion in the {@link ListenableFuture#addListener
* ListenableFuture.addListener} documentation. All its warnings about heavyweight listeners are
* also applicable to heavyweight functions passed to this method. (Specifically, {@code
* directExecutor} functions should avoid heavyweight operations inside {@code
* AsyncFunction.apply}. Any heavyweight operations should occur in other threads responsible for
* completing the returned {@code Future}.)
*
* @param input the primary input {@code Future}
* @param exceptionType the exception type that triggers use of {@code fallback}. The exception
* type is matched against the input's exception. "The input's exception" means the cause of
* the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
* different kind of exception, that exception itself. To avoid hiding bugs and other
* unrecoverable errors, callers should prefer more specific types, avoiding {@code
* Throwable.class} in particular.
* @param fallback the {@link AsyncFunction} to be called if {@code input} fails with the expected
* exception type. The function's argument is the input's exception. "The input's exception"
* means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
* {@code get()} throws a different kind of exception, that exception itself.
* @since 19.0 (similar functionality in 14.0 as {@code withFallback})
* @deprecated Use {@linkplain #catchingAsync(ListenableFuture, Class, AsyncFunction, Executor)
* the overload that requires an executor}. For identical behavior, pass {@link
* MoreExecutors#directExecutor}, but consider whether another executor would be safer, as
* discussed in the {@link ListenableFuture#addListener ListenableFuture.addListener}
* documentation. This method is scheduled to be removed in July 2018.
*/
@CanIgnoreReturnValue // TODO(kak): @CheckReturnValue
@Deprecated
@DoNotCall
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
public static <V, X extends Throwable> ListenableFuture<V> catchingAsync(
ListenableFuture<? extends V> input,
Class<X> exceptionType,
AsyncFunction<? super X, ? extends V> fallback) {
return AbstractCatchingFuture.create(input, exceptionType, fallback, directExecutor());
}
/**
* Returns a {@code Future} whose result is taken from the given primary {@code input} or, if the
* primary input fails with the given {@code exceptionType}, from the result provided by the
* {@code fallback}. {@link AsyncFunction#apply} is not invoked until the primary input has
* failed, so if the primary input succeeds, it is never invoked. If, during the invocation of
* {@code fallback}, an exception is thrown, this exception is used as the result of the output
* {@code Future}.
*
* <p>Usage examples:
*
* <pre>{@code
* ListenableFuture<Integer> fetchCounterFuture = ...;
*
* // Falling back to a zero counter in case an exception happens when
* // processing the RPC to fetch counters.
* ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
* fetchCounterFuture, FetchException.class, x -> immediateFuture(0), directExecutor());
* }</pre>
*
* <p>The fallback can also choose to propagate the original exception when desired:
*
* <pre>{@code
* ListenableFuture<Integer> fetchCounterFuture = ...;
*
* // Falling back to a zero counter only in case the exception was a
* // TimeoutException.
* ListenableFuture<Integer> faultTolerantFuture = Futures.catchingAsync(
* fetchCounterFuture,
* FetchException.class,
* e -> {
* if (omitDataOnFetchFailure) {
* return immediateFuture(0);
* }
* throw e;
* },
* directExecutor());
* }</pre>
*
* <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
* the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
* documentation. All its warnings about heavyweight listeners are also applicable to heavyweight
* functions passed to this method. (Specifically, {@code directExecutor} functions should avoid
* heavyweight operations inside {@code AsyncFunction.apply}. Any heavyweight operations should
* occur in other threads responsible for completing the returned {@code Future}.)
*
* @param input the primary input {@code Future}
* @param exceptionType the exception type that triggers use of {@code fallback}. The exception
* type is matched against the input's exception. "The input's exception" means the cause of
* the {@link ExecutionException} thrown by {@code input.get()} or, if {@code get()} throws a
* different kind of exception, that exception itself. To avoid hiding bugs and other
* unrecoverable errors, callers should prefer more specific types, avoiding {@code
* Throwable.class} in particular.
* @param fallback the {@link AsyncFunction} to be called if {@code input} fails with the expected
* exception type. The function's argument is the input's exception. "The input's exception"
* means the cause of the {@link ExecutionException} thrown by {@code input.get()} or, if
* {@code get()} throws a different kind of exception, that exception itself.
* @param executor the executor that runs {@code fallback} if {@code input} fails
* @since 19.0 (similar functionality in 14.0 as {@code withFallback})
*/
@CanIgnoreReturnValue // TODO(kak): @CheckReturnValue
@Partially.GwtIncompatible("AVAILABLE but requires exceptionType to be Throwable.class")
public static <V, X extends Throwable> ListenableFuture<V> catchingAsync(
ListenableFuture<? extends V> input,
Class<X> exceptionType,
AsyncFunction<? super X, ? extends V> fallback,
Executor executor) {
return AbstractCatchingFuture.create(input, exceptionType, fallback, executor);
}
/**
* Returns a future that delegates to another but will finish early (via a {@link
* TimeoutException} wrapped in an {@link ExecutionException}) if the specified duration expires.
*
* <p>The delegate future is interrupted and cancelled if it times out.
*
* @param delegate The future to delegate to.
* @param time when to timeout the future
* @param unit the time unit of the time parameter
* @param scheduledExecutor The executor service to enforce the timeout.
* @since 19.0
*/
@GwtIncompatible // java.util.concurrent.ScheduledExecutorService
public static <V> ListenableFuture<V> withTimeout(
ListenableFuture<V> delegate,
long time,
TimeUnit unit,
ScheduledExecutorService scheduledExecutor) {
return TimeoutFuture.create(delegate, time, unit, scheduledExecutor);
}
/**
* Returns a new {@code Future} whose result is asynchronously derived from the result of the
* given {@code Future}. If the given {@code Future} fails, the returned {@code Future} fails with
* the same exception (and the function is not invoked).
*
* <p>More precisely, the returned {@code Future} takes its result from a {@code Future} produced
* by applying the given {@code AsyncFunction} to the result of the original {@code Future}.
* Example usage:
*
* <pre>{@code
* ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
* ListenableFuture<QueryResult> queryFuture =
* transformAsync(rowKeyFuture, dataService::readFuture);
* }</pre>
*
* <p>This overload, which does not accept an executor, uses {@code directExecutor}, a dangerous
* choice in some cases. See the discussion in the {@link ListenableFuture#addListener
* ListenableFuture.addListener} documentation. All its warnings about heavyweight listeners are
* also applicable to heavyweight functions passed to this method. (Specifically, {@code
* directExecutor} functions should avoid heavyweight operations inside {@code
* AsyncFunction.apply}. Any heavyweight operations should occur in other threads responsible for
* completing the returned {@code Future}.)
*
* <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
* input future and that of the future returned by the function. That is, if the returned {@code
* Future} is cancelled, it will attempt to cancel the other two, and if either of the other two
* is cancelled, the returned {@code Future} will receive a callback in which it will attempt to
* cancel itself.
*
* @param input The future to transform
* @param function A function to transform the result of the input future to the result of the
* output future
* @return A future that holds result of the function (if the input succeeded) or the original
* input's failure (if not)
* @since 19.0 (in 11.0 as {@code transform})
* @deprecated Use {@linkplain #transformAsync(ListenableFuture, AsyncFunction, Executor) the
* overload that requires an executor}. For identical behavior, pass {@link
* MoreExecutors#directExecutor}, but consider whether another executor would be safer, as
* discussed in the {@link ListenableFuture#addListener ListenableFuture.addListener}
* documentation. This method is scheduled to be removed in July 2018.
*/
@Deprecated
@DoNotCall
public static <I, O> ListenableFuture<O> transformAsync(
ListenableFuture<I> input, AsyncFunction<? super I, ? extends O> function) {
return AbstractTransformFuture.create(input, function, directExecutor());
}
/**
* Returns a new {@code Future} whose result is asynchronously derived from the result of the
* given {@code Future}. If the given {@code Future} fails, the returned {@code Future} fails with
* the same exception (and the function is not invoked).
*
* <p>More precisely, the returned {@code Future} takes its result from a {@code Future} produced
* by applying the given {@code AsyncFunction} to the result of the original {@code Future}.
* Example usage:
*
* <pre>{@code
* ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
* ListenableFuture<QueryResult> queryFuture =
* transformAsync(rowKeyFuture, dataService::readFuture, executor);
* }</pre>
*
* <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
* the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
* documentation. All its warnings about heavyweight listeners are also applicable to heavyweight
* functions passed to this method. (Specifically, {@code directExecutor} functions should avoid
* heavyweight operations inside {@code AsyncFunction.apply}. Any heavyweight operations should
* occur in other threads responsible for completing the returned {@code Future}.)
*
* <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
* input future and that of the future returned by the chain function. That is, if the returned
* {@code Future} is cancelled, it will attempt to cancel the other two, and if either of the
* other two is cancelled, the returned {@code Future} will receive a callback in which it will
* attempt to cancel itself.
*
* @param input The future to transform
* @param function A function to transform the result of the input future to the result of the
* output future
* @param executor Executor to run the function in.
* @return A future that holds result of the function (if the input succeeded) or the original
* input's failure (if not)
* @since 19.0 (in 11.0 as {@code transform})
*/
public static <I, O> ListenableFuture<O> transformAsync(
ListenableFuture<I> input,
AsyncFunction<? super I, ? extends O> function,
Executor executor) {
return AbstractTransformFuture.create(input, function, executor);
}
/**
* Returns a new {@code Future} whose result is derived from the result of the given {@code
* Future}. If {@code input} fails, the returned {@code Future} fails with the same exception (and
* the function is not invoked). Example usage:
*
* <pre>{@code
* ListenableFuture<QueryResult> queryFuture = ...;
* ListenableFuture<List<Row>> rowsFuture =
* transform(queryFuture, QueryResult::getRows);
* }</pre>
*
* <p>This overload, which does not accept an executor, uses {@code directExecutor}, a dangerous
* choice in some cases. See the discussion in the {@link ListenableFuture#addListener
* ListenableFuture.addListener} documentation. All its warnings about heavyweight listeners are
* also applicable to heavyweight functions passed to this method.
*
* <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
* input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel
* the input, and if the input is cancelled, the returned {@code Future} will receive a callback
* in which it will attempt to cancel itself.
*
* <p>An example use of this method is to convert a serializable object returned from an RPC into
* a POJO.
*
* @param input The future to transform
* @param function A Function to transform the results of the provided future to the results of
* the returned future. This will be run in the thread that notifies input it is complete.
* @return A future that holds result of the transformation.
* @since 9.0 (in 1.0 as {@code compose})
* @deprecated Use {@linkplain #transform(ListenableFuture, Function, Executor) the overload that
* requires an executor}. For identical behavior, pass {@link MoreExecutors#directExecutor},
* but consider whether another executor would be safer, as discussed in the {@link
* ListenableFuture#addListener ListenableFuture.addListener} documentation. This method is
* scheduled to be removed in July 2018.
*/
@Deprecated
@DoNotCall
public static <I, O> ListenableFuture<O> transform(
ListenableFuture<I> input, Function<? super I, ? extends O> function) {
return AbstractTransformFuture.create(input, function, directExecutor());
}
/**
* Returns a new {@code Future} whose result is derived from the result of the given {@code
* Future}. If {@code input} fails, the returned {@code Future} fails with the same exception (and
* the function is not invoked). Example usage:
*
* <pre>{@code
* ListenableFuture<QueryResult> queryFuture = ...;
* ListenableFuture<List<Row>> rowsFuture =
* transform(queryFuture, QueryResult::getRows, executor);
* }</pre>
*
* <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
* the discussion in the {@link ListenableFuture#addListener ListenableFuture.addListener}
* documentation. All its warnings about heavyweight listeners are also applicable to heavyweight
* functions passed to this method.
*
* <p>The returned {@code Future} attempts to keep its cancellation state in sync with that of the
* input future. That is, if the returned {@code Future} is cancelled, it will attempt to cancel
* the input, and if the input is cancelled, the returned {@code Future} will receive a callback
* in which it will attempt to cancel itself.
*
* <p>An example use of this method is to convert a serializable object returned from an RPC into
* a POJO.
*
* @param input The future to transform
* @param function A Function to transform the results of the provided future to the results of
* the returned future.
* @param executor Executor to run the function in.
* @return A future that holds result of the transformation.
* @since 9.0 (in 2.0 as {@code compose})
*/
public static <I, O> ListenableFuture<O> transform(
ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor) {
return AbstractTransformFuture.create(input, function, executor);
}
/**
* Like {@link #transform(ListenableFuture, Function, Executor)} except that the transformation
* {@code function} is invoked on each call to {@link Future#get() get()} on the returned future.
*
* <p>The returned {@code Future} reflects the input's cancellation state directly, and any
* attempt to cancel the returned Future is likewise passed through to the input Future.
*
* <p>Note that calls to {@linkplain Future#get(long, TimeUnit) timed get} only apply the timeout
* to the execution of the underlying {@code Future}, <em>not</em> to the execution of the
* transformation function.
*
* <p>The primary audience of this method is callers of {@code transform} who don't have a {@code
* ListenableFuture} available and do not mind repeated, lazy function evaluation.
*
* @param input The future to transform
* @param function A Function to transform the results of the provided future to the results of
* the returned future.
* @return A future that returns the result of the transformation.
* @since 10.0
*/
@GwtIncompatible // TODO
public static <I, O> Future<O> lazyTransform(
final Future<I> input, final Function<? super I, ? extends O> function) {
checkNotNull(input);
checkNotNull(function);
return new Future<O>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return input.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return input.isCancelled();
}
@Override
public boolean isDone() {
return input.isDone();
}
@Override
public O get() throws InterruptedException, ExecutionException {
return applyTransformation(input.get());
}
@Override
public O get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return applyTransformation(input.get(timeout, unit));
}
private O applyTransformation(I input) throws ExecutionException {
try {
return function.apply(input);
} catch (Throwable t) {
throw new ExecutionException(t);
}
}
};
}
/**
* Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
* input futures, if all succeed.
*
* <p>The list of results is in the same order as the input list.
*
* <p>Canceling this future will attempt to cancel all the component futures, and if any of the
* provided futures fails or is canceled, this one is, too.
*
* @param futures futures to combine
* @return a future that provides a list of the results of the component futures
* @since 10.0
*/
@Beta
@SafeVarargs
public static <V> ListenableFuture<List<V>> allAsList(ListenableFuture<? extends V>... futures) {
return new ListFuture<V>(ImmutableList.copyOf(futures), true);
}
/**
* Creates a new {@code ListenableFuture} whose value is a list containing the values of all its
* input futures, if all succeed.
*
* <p>The list of results is in the same order as the input list.
*
* <p>Canceling this future will attempt to cancel all the component futures, and if any of the
* provided futures fails or is canceled, this one is, too.
*
* @param futures futures to combine
* @return a future that provides a list of the results of the component futures
* @since 10.0
*/
@Beta
public static <V> ListenableFuture<List<V>> allAsList(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return new ListFuture<V>(ImmutableList.copyOf(futures), true);
}
/**
* Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
* successful.
*
* @since 20.0
*/
@SafeVarargs
public static <V> FutureCombiner<V> whenAllComplete(ListenableFuture<? extends V>... futures) {
return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
}
/**
* Creates a {@link FutureCombiner} that processes the completed futures whether or not they're
* successful.
*
* @since 20.0
*/
public static <V> FutureCombiner<V> whenAllComplete(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return new FutureCombiner<V>(false, ImmutableList.copyOf(futures));
}
/**
* Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
*
* <p>If any input fails, the returned future fails immediately.
*
* @since 20.0
*/
@SafeVarargs
public static <V> FutureCombiner<V> whenAllSucceed(ListenableFuture<? extends V>... futures) {
return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
}
/**
* Creates a {@link FutureCombiner} requiring that all passed in futures are successful.
*
* <p>If any input fails, the returned future fails immediately.
*
* @since 20.0
*/
public static <V> FutureCombiner<V> whenAllSucceed(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return new FutureCombiner<V>(true, ImmutableList.copyOf(futures));
}
/**
* A helper to create a new {@code ListenableFuture} whose result is generated from a combination
* of input futures.
*
* <p>See {@link #whenAllComplete} and {@link #whenAllSucceed} for how to instantiate this class.
*
* <p>Example:
*
* <pre>{@code
* final ListenableFuture<Instant> loginDateFuture =
* loginService.findLastLoginDate(username);
* final ListenableFuture<List<String>> recentCommandsFuture =
* recentCommandsService.findRecentCommands(username);
* Callable<UsageHistory> usageComputation =
* new Callable<UsageHistory>() {
* public UsageHistory call() throws Exception {
* return new UsageHistory(
* username, loginDateFuture.get(), recentCommandsFuture.get());
* }
* };
* ListenableFuture<UsageHistory> usageFuture =
* Futures.whenAllSucceed(loginDateFuture, recentCommandsFuture)
* .call(usageComputation, executor);
* }</pre>
*
* @since 20.0
*/
@Beta
@CanIgnoreReturnValue // TODO(cpovirk): Consider removing, especially if we provide run(Runnable)
@GwtCompatible
public static final class FutureCombiner<V> {
private final boolean allMustSucceed;
private final ImmutableList<ListenableFuture<? extends V>> futures;
private FutureCombiner(
boolean allMustSucceed, ImmutableList<ListenableFuture<? extends V>> futures) {
this.allMustSucceed = allMustSucceed;
this.futures = futures;
}
/**
* Creates the {@link ListenableFuture} which will return the result of calling {@link
* AsyncCallable#call} in {@code combiner} when all futures complete, using the specified {@code
* executor}.
*
* <p>If the combiner throws a {@code CancellationException}, the returned future will be
* cancelled.
*
* <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
* ExecutionException} will be extracted and returned as the cause of the new {@code
* ExecutionException} that gets thrown by the returned combined future.
*
* <p>Canceling this future will attempt to cancel all the component futures.
*/
public <C> ListenableFuture<C> callAsync(AsyncCallable<C> combiner, Executor executor) {
return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner);
}
/**
* Like {@link #callAsync(AsyncCallable, Executor)} but using {@linkplain
* MoreExecutors#directExecutor direct executor}.
*
* @deprecated Use {@linkplain #callAsync(AsyncCallable, Executor) the overload that requires an
* executor}. For identical behavior, pass {@link MoreExecutors#directExecutor}, but
* consider whether another executor would be safer, as discussed in the {@link
* ListenableFuture#addListener ListenableFuture.addListener} documentation. This method is
* scheduled to be removed in July 2018.
*/
@Deprecated
@DoNotCall
public <C> ListenableFuture<C> callAsync(AsyncCallable<C> combiner) {
return callAsync(combiner, directExecutor());
}
/**
* Creates the {@link ListenableFuture} which will return the result of calling {@link
* Callable#call} in {@code combiner} when all futures complete, using the specified {@code
* executor}.
*
* <p>If the combiner throws a {@code CancellationException}, the returned future will be
* cancelled.
*
* <p>If the combiner throws an {@code ExecutionException}, the cause of the thrown {@code
* ExecutionException} will be extracted and returned as the cause of the new {@code
* ExecutionException} that gets thrown by the returned combined future.
*
* <p>Canceling this future will attempt to cancel all the component futures.
*/
@CanIgnoreReturnValue // TODO(cpovirk): Remove this
public <C> ListenableFuture<C> call(Callable<C> combiner, Executor executor) {
return new CombinedFuture<C>(futures, allMustSucceed, executor, combiner);
}
/**
* Like {@link #call(Callable, Executor)} but using {@linkplain MoreExecutors#directExecutor
* direct executor}.
*
* @deprecated Use {@linkplain #call(Callable, Executor) the overload that requires an
* executor}. For identical behavior, pass {@link MoreExecutors#directExecutor}, but
* consider whether another executor would be safer, as discussed in the {@link
* ListenableFuture#addListener ListenableFuture.addListener} documentation. This method is
* scheduled to be removed in July 2018.
*/
@CanIgnoreReturnValue // TODO(cpovirk): Remove this
@Deprecated
@DoNotCall
public <C> ListenableFuture<C> call(Callable<C> combiner) {
return call(combiner, directExecutor());
}
/**
* Creates the {@link ListenableFuture} which will return the result of running {@code combiner}
* when all Futures complete. {@code combiner} will run using {@code executor}.
*
* <p>If the combiner throws a {@code CancellationException}, the returned future will be
* cancelled.
*
* <p>Canceling this Future will attempt to cancel all the component futures.
*
* @since 23.6
*/
public ListenableFuture<?> run(final Runnable combiner, Executor executor) {
return call(
new Callable<Void>() {
@Override
public Void call() throws Exception {
combiner.run();
return null;
}
},
executor);
}
}
/**
* Returns a {@code ListenableFuture} whose result is set from the supplied future when it
* completes. Cancelling the supplied future will also cancel the returned future, but cancelling
* the returned future will have no effect on the supplied future.
*