aboutsummaryrefslogtreecommitdiff
path: root/guava/src/com/google/common/util/concurrent/ClosingFuture.java
blob: efdf56d8aa52a4919f692f2676a3597cec86a05c (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
/*
 * Copyright (C) 2017 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.Functions.constant;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Lists.asList;
import static com.google.common.util.concurrent.ClosingFuture.State.CLOSED;
import static com.google.common.util.concurrent.ClosingFuture.State.CLOSING;
import static com.google.common.util.concurrent.ClosingFuture.State.OPEN;
import static com.google.common.util.concurrent.ClosingFuture.State.SUBSUMED;
import static com.google.common.util.concurrent.ClosingFuture.State.WILL_CLOSE;
import static com.google.common.util.concurrent.ClosingFuture.State.WILL_CREATE_VALUE_AND_CLOSER;
import static com.google.common.util.concurrent.Futures.getDone;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static com.google.common.util.concurrent.Futures.nonCancellationPropagating;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
import static java.util.logging.Level.FINER;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Level.WARNING;

import com.google.common.annotations.J2ktIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ClosingFuture.Combiner.AsyncCombiningCallable;
import com.google.common.util.concurrent.ClosingFuture.Combiner.CombiningCallable;
import com.google.common.util.concurrent.Futures.FutureCombiner;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.DoNotMock;
import com.google.j2objc.annotations.RetainedWith;
import java.io.Closeable;
import java.util.IdentityHashMap;
import java.util.Map;
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.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A step in a pipeline of an asynchronous computation. When the last step in the computation is
 * complete, some objects captured during the computation are closed.
 *
 * <p>A pipeline of {@code ClosingFuture}s is a tree of steps. Each step represents either an
 * asynchronously-computed intermediate value, or else an exception that indicates the failure or
 * cancellation of the operation so far. The only way to extract the value or exception from a step
 * is by declaring that step to be the last step of the pipeline. Nevertheless, we refer to the
 * "value" of a successful step or the "result" (value or exception) of any step.
 *
 * <ol>
 *   <li>A pipeline starts at its leaf step (or steps), which is created from either a callable
 *       block or a {@link ListenableFuture}.
 *   <li>Each other step is derived from one or more input steps. At each step, zero or more objects
 *       can be captured for later closing.
 *   <li>There is one last step (the root of the tree), from which you can extract the final result
 *       of the computation. After that result is available (or the computation fails), all objects
 *       captured by any of the steps in the pipeline are closed.
 * </ol>
 *
 * <h3>Starting a pipeline</h3>
 *
 * Start a {@code ClosingFuture} pipeline {@linkplain #submit(ClosingCallable, Executor) from a
 * callable block} that may capture objects for later closing. To start a pipeline from a {@link
 * ListenableFuture} that doesn't create resources that should be closed later, you can use {@link
 * #from(ListenableFuture)} instead.
 *
 * <h3>Derived steps</h3>
 *
 * A {@code ClosingFuture} step can be derived from one or more input {@code ClosingFuture} steps in
 * ways similar to {@link FluentFuture}s:
 *
 * <ul>
 *   <li>by transforming the value from a successful input step,
 *   <li>by catching the exception from a failed input step, or
 *   <li>by combining the results of several input steps.
 * </ul>
 *
 * Each derivation can capture the next value or any intermediate objects for later closing.
 *
 * <p>A step can be the input to at most one derived step. Once you transform its value, catch its
 * exception, or combine it with others, you cannot do anything else with it, including declare it
 * to be the last step of the pipeline.
 *
 * <h4>Transforming</h4>
 *
 * To derive the next step by asynchronously applying a function to an input step's value, call
 * {@link #transform(ClosingFunction, Executor)} or {@link #transformAsync(AsyncClosingFunction,
 * Executor)} on the input step.
 *
 * <h4>Catching</h4>
 *
 * To derive the next step from a failed input step, call {@link #catching(Class, ClosingFunction,
 * Executor)} or {@link #catchingAsync(Class, AsyncClosingFunction, Executor)} on the input step.
 *
 * <h4>Combining</h4>
 *
 * To derive a {@code ClosingFuture} from two or more input steps, pass the input steps to {@link
 * #whenAllComplete(Iterable)} or {@link #whenAllSucceed(Iterable)} or its overloads.
 *
 * <h3>Cancelling</h3>
 *
 * Any step in a pipeline can be {@linkplain #cancel(boolean) cancelled}, even after another step
 * has been derived, with the same semantics as cancelling a {@link Future}. In addition, a
 * successfully cancelled step will immediately start closing all objects captured for later closing
 * by it and by its input steps.
 *
 * <h3>Ending a pipeline</h3>
 *
 * Each {@code ClosingFuture} pipeline must be ended. To end a pipeline, decide whether you want to
 * close the captured objects automatically or manually.
 *
 * <h4>Automatically closing</h4>
 *
 * You can extract a {@link Future} that represents the result of the last step in the pipeline by
 * calling {@link #finishToFuture()}. All objects the pipeline has captured for closing will begin
 * to be closed asynchronously <b>after</b> the returned {@code Future} is done: the future
 * completes before closing starts, rather than once it has finished.
 *
 * <pre>{@code
 * FluentFuture<UserName> userName =
 *     ClosingFuture.submit(
 *             closer -> closer.eventuallyClose(database.newTransaction(), closingExecutor),
 *             executor)
 *         .transformAsync((closer, transaction) -> transaction.queryClosingFuture("..."), executor)
 *         .transform((closer, result) -> result.get("userName"), directExecutor())
 *         .catching(DBException.class, e -> "no user", directExecutor())
 *         .finishToFuture();
 * }</pre>
 *
 * In this example, when the {@code userName} {@link Future} is done, the transaction and the query
 * result cursor will both be closed, even if the operation is cancelled or fails.
 *
 * <h4>Manually closing</h4>
 *
 * If you want to close the captured objects manually, after you've used the final result, call
 * {@link #finishToValueAndCloser(ValueAndCloserConsumer, Executor)} to get an object that holds the
 * final result. You then call {@link ValueAndCloser#closeAsync()} to close the captured objects.
 *
 * <pre>{@code
 *     ClosingFuture.submit(
 *             closer -> closer.eventuallyClose(database.newTransaction(), closingExecutor),
 *             executor)
 *     .transformAsync((closer, transaction) -> transaction.queryClosingFuture("..."), executor)
 *     .transform((closer, result) -> result.get("userName"), directExecutor())
 *     .catching(DBException.class, e -> "no user", directExecutor())
 *     .finishToValueAndCloser(
 *         valueAndCloser -> this.userNameValueAndCloser = valueAndCloser, executor);
 *
 * // later
 * try { // get() will throw if the operation failed or was cancelled.
 *   UserName userName = userNameValueAndCloser.get();
 *   // do something with userName
 * } finally {
 *   userNameValueAndCloser.closeAsync();
 * }
 * }</pre>
 *
 * In this example, when {@code userNameValueAndCloser.closeAsync()} is called, the transaction and
 * the query result cursor will both be closed, even if the operation is cancelled or fails.
 *
 * <p>Note that if you don't call {@code closeAsync()}, the captured objects will not be closed. The
 * automatic-closing approach described above is safer.
 *
 * @param <V> the type of the value of this step
 * @since 30.0
 */
// TODO(dpb): Consider reusing one CloseableList for the entire pipeline, modulo combinations.
@DoNotMock("Use ClosingFuture.from(Futures.immediate*Future)")
@J2ktIncompatible
@ElementTypesAreNonnullByDefault
// TODO(dpb): GWT compatibility.
public final class ClosingFuture<V extends @Nullable Object> {

  private static final LazyLogger logger = new LazyLogger(ClosingFuture.class);

  /**
   * An object that can capture objects to be closed later, when a {@link ClosingFuture} pipeline is
   * done.
   */
  public static final class DeferredCloser {
    @RetainedWith private final CloseableList list;

    DeferredCloser(CloseableList list) {
      this.list = list;
    }

    /**
     * Captures an object to be closed when a {@link ClosingFuture} pipeline is done.
     *
     * <p>For users of the {@code -jre} flavor of Guava, the object can be any {@code
     * AutoCloseable}. For users of the {@code -android} flavor, the object must be a {@code
     * Closeable}. (For more about the flavors, see <a
     * href="https://github.com/google/guava#adding-guava-to-your-build">Adding Guava to your
     * build</a>.)
     *
     * <p>Be careful when targeting an older SDK than you are building against (most commonly when
     * building for Android): Ensure that any object you pass implements the interface not just in
     * your current SDK version but also at the oldest version you support. For example, <a
     * href="https://developer.android.com/sdk/api_diff/16/">API Level 16</a> is the first version
     * in which {@code Cursor} is {@code Closeable}. To support older versions, pass a wrapper
     * {@code Closeable} with a method reference like {@code cursor::close}.
     *
     * <p>Note that this method is still binary-compatible between flavors because the erasure of
     * its parameter type is {@code Object}, not {@code AutoCloseable} or {@code Closeable}.
     *
     * @param closeable the object to be closed (see notes above)
     * @param closingExecutor the object will be closed on this executor
     * @return the first argument
     */
    @CanIgnoreReturnValue
    @ParametricNullness
    public <C extends @Nullable Object & @Nullable AutoCloseable> C eventuallyClose(
        @ParametricNullness C closeable, Executor closingExecutor) {
      checkNotNull(closingExecutor);
      if (closeable != null) {
        list.add(closeable, closingExecutor);
      }
      return closeable;
    }
  }

  /**
   * An operation that computes a result.
   *
   * @param <V> the type of the result
   */
  @FunctionalInterface
  public interface ClosingCallable<V extends @Nullable Object> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
     * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
     * not before this method completes), even if this method throws or the pipeline is cancelled.
     */
    @ParametricNullness
    V call(DeferredCloser closer) throws Exception;
  }

  /**
   * An operation that computes a {@link ClosingFuture} of a result.
   *
   * @param <V> the type of the result
   * @since 30.1
   */
  @FunctionalInterface
  public interface AsyncClosingCallable<V extends @Nullable Object> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
     * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
     * not before this method completes), even if this method throws or the pipeline is cancelled.
     */
    ClosingFuture<V> call(DeferredCloser closer) throws Exception;
  }

  /**
   * A function from an input to a result.
   *
   * @param <T> the type of the input to the function
   * @param <U> the type of the result of the function
   */
  @FunctionalInterface
  public interface ClosingFunction<T extends @Nullable Object, U extends @Nullable Object> {

    /**
     * Applies this function to an input, or throws an exception if unable to do so.
     *
     * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
     * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
     * not before this method completes), even if this method throws or the pipeline is cancelled.
     */
    @ParametricNullness
    U apply(DeferredCloser closer, @ParametricNullness T input) throws Exception;
  }

  /**
   * A function from an input to a {@link ClosingFuture} of a result.
   *
   * @param <T> the type of the input to the function
   * @param <U> the type of the result of the function
   */
  @FunctionalInterface
  public interface AsyncClosingFunction<T extends @Nullable Object, U extends @Nullable Object> {
    /**
     * Applies this function to an input, or throws an exception if unable to do so.
     *
     * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
     * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
     * not before this method completes), even if this method throws or the pipeline is cancelled.
     */
    ClosingFuture<U> apply(DeferredCloser closer, @ParametricNullness T input) throws Exception;
  }

  /**
   * An object that holds the final result of an asynchronous {@link ClosingFuture} operation and
   * allows the user to close all the closeable objects that were captured during it for later
   * closing.
   *
   * <p>The asynchronous operation will have completed before this object is created.
   *
   * @param <V> the type of the value of a successful operation
   * @see ClosingFuture#finishToValueAndCloser(ValueAndCloserConsumer, Executor)
   */
  public static final class ValueAndCloser<V extends @Nullable Object> {

    private final ClosingFuture<? extends V> closingFuture;

    ValueAndCloser(ClosingFuture<? extends V> closingFuture) {
      this.closingFuture = checkNotNull(closingFuture);
    }

    /**
     * Returns the final value of the associated {@link ClosingFuture}, or throws an exception as
     * {@link Future#get()} would.
     *
     * <p>Because the asynchronous operation has already completed, this method is synchronous and
     * returns immediately.
     *
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an exception
     */
    @ParametricNullness
    public V get() throws ExecutionException {
      return getDone(closingFuture.future);
    }

    /**
     * Starts closing all closeable objects captured during the {@link ClosingFuture}'s asynchronous
     * operation on the {@link Executor}s specified by calls to {@link
     * DeferredCloser#eventuallyClose(Object, Executor)}.
     *
     * <p>If any such calls specified {@link MoreExecutors#directExecutor()}, those objects will be
     * closed synchronously.
     *
     * <p>Idempotent: objects will be closed at most once.
     */
    public void closeAsync() {
      closingFuture.close();
    }
  }

  /**
   * Represents an operation that accepts a {@link ValueAndCloser} for the last step in a {@link
   * ClosingFuture} pipeline.
   *
   * @param <V> the type of the final value of a successful pipeline
   * @see ClosingFuture#finishToValueAndCloser(ValueAndCloserConsumer, Executor)
   */
  @FunctionalInterface
  public interface ValueAndCloserConsumer<V extends @Nullable Object> {

    /** Accepts a {@link ValueAndCloser} for the last step in a {@link ClosingFuture} pipeline. */
    void accept(ValueAndCloser<V> valueAndCloser);
  }

  /**
   * Starts a {@link ClosingFuture} pipeline by submitting a callable block to an executor.
   *
   * @throws java.util.concurrent.RejectedExecutionException if the task cannot be scheduled for
   *     execution
   */
  public static <V extends @Nullable Object> ClosingFuture<V> submit(
      ClosingCallable<V> callable, Executor executor) {
    return new ClosingFuture<>(callable, executor);
  }

  /**
   * Starts a {@link ClosingFuture} pipeline by submitting a callable block to an executor.
   *
   * @throws java.util.concurrent.RejectedExecutionException if the task cannot be scheduled for
   *     execution
   * @since 30.1
   */
  public static <V extends @Nullable Object> ClosingFuture<V> submitAsync(
      AsyncClosingCallable<V> callable, Executor executor) {
    return new ClosingFuture<>(callable, executor);
  }

  /**
   * Starts a {@link ClosingFuture} pipeline with a {@link ListenableFuture}.
   *
   * <p>{@code future}'s value will not be closed when the pipeline is done even if {@code V}
   * implements {@link Closeable}. In order to start a pipeline with a value that will be closed
   * when the pipeline is done, use {@link #submit(ClosingCallable, Executor)} instead.
   */
  public static <V extends @Nullable Object> ClosingFuture<V> from(ListenableFuture<V> future) {
    return new ClosingFuture<V>(future);
  }

  /**
   * Starts a {@link ClosingFuture} pipeline with a {@link ListenableFuture}.
   *
   * <p>If {@code future} succeeds, its value will be closed (using {@code closingExecutor)}) when
   * the pipeline is done, even if the pipeline is canceled or fails.
   *
   * <p>Cancelling the pipeline will not cancel {@code future}, so that the pipeline can access its
   * value in order to close it.
   *
   * @param future the future to create the {@code ClosingFuture} from. For discussion of the
   *     future's result type {@code C}, see {@link DeferredCloser#eventuallyClose(Object,
   *     Executor)}.
   * @param closingExecutor the future's result will be closed on this executor
   * @deprecated Creating {@link Future}s of closeable types is dangerous in general because the
   *     underlying value may never be closed if the {@link Future} is canceled after its operation
   *     begins. Consider replacing code that creates {@link ListenableFuture}s of closeable types,
   *     including those that pass them to this method, with {@link #submit(ClosingCallable,
   *     Executor)} in order to ensure that resources do not leak. Or, to start a pipeline with a
   *     {@link ListenableFuture} that doesn't create values that should be closed, use {@link
   *     ClosingFuture#from}.
   */
  @Deprecated
  public static <C extends @Nullable Object & @Nullable AutoCloseable>
      ClosingFuture<C> eventuallyClosing(
          ListenableFuture<C> future, final Executor closingExecutor) {
    checkNotNull(closingExecutor);
    final ClosingFuture<C> closingFuture = new ClosingFuture<>(nonCancellationPropagating(future));
    Futures.addCallback(
        future,
        new FutureCallback<@Nullable AutoCloseable>() {
          @Override
          public void onSuccess(@CheckForNull AutoCloseable result) {
            closingFuture.closeables.closer.eventuallyClose(result, closingExecutor);
          }

          @Override
          public void onFailure(Throwable t) {}
        },
        directExecutor());
    return closingFuture;
  }

  /**
   * Starts specifying how to combine {@link ClosingFuture}s into a single pipeline.
   *
   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
   *     the {@code futures}, or if any has already been {@linkplain #finishToFuture() finished}
   */
  public static Combiner whenAllComplete(Iterable<? extends ClosingFuture<?>> futures) {
    return new Combiner(false, futures);
  }

  /**
   * Starts specifying how to combine {@link ClosingFuture}s into a single pipeline.
   *
   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
   */
  public static Combiner whenAllComplete(
      ClosingFuture<?> future1, ClosingFuture<?>... moreFutures) {
    return whenAllComplete(asList(future1, moreFutures));
  }

  /**
   * Starts specifying how to combine {@link ClosingFuture}s into a single pipeline, assuming they
   * all succeed. If any fail, the resulting pipeline will fail.
   *
   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
   *     the {@code futures}, or if any has already been {@linkplain #finishToFuture() finished}
   */
  public static Combiner whenAllSucceed(Iterable<? extends ClosingFuture<?>> futures) {
    return new Combiner(true, futures);
  }

  /**
   * Starts specifying how to combine two {@link ClosingFuture}s into a single pipeline, assuming
   * they all succeed. If any fail, the resulting pipeline will fail.
   *
   * <p>Calling this method allows you to use lambdas or method references typed with the types of
   * the input {@link ClosingFuture}s.
   *
   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
   */
  public static <V1 extends @Nullable Object, V2 extends @Nullable Object>
      Combiner2<V1, V2> whenAllSucceed(ClosingFuture<V1> future1, ClosingFuture<V2> future2) {
    return new Combiner2<>(future1, future2);
  }

  /**
   * Starts specifying how to combine three {@link ClosingFuture}s into a single pipeline, assuming
   * they all succeed. If any fail, the resulting pipeline will fail.
   *
   * <p>Calling this method allows you to use lambdas or method references typed with the types of
   * the input {@link ClosingFuture}s.
   *
   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
   */
  public static <
          V1 extends @Nullable Object, V2 extends @Nullable Object, V3 extends @Nullable Object>
      Combiner3<V1, V2, V3> whenAllSucceed(
          ClosingFuture<V1> future1, ClosingFuture<V2> future2, ClosingFuture<V3> future3) {
    return new Combiner3<>(future1, future2, future3);
  }

  /**
   * Starts specifying how to combine four {@link ClosingFuture}s into a single pipeline, assuming
   * they all succeed. If any fail, the resulting pipeline will fail.
   *
   * <p>Calling this method allows you to use lambdas or method references typed with the types of
   * the input {@link ClosingFuture}s.
   *
   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
   */
  public static <
          V1 extends @Nullable Object,
          V2 extends @Nullable Object,
          V3 extends @Nullable Object,
          V4 extends @Nullable Object>
      Combiner4<V1, V2, V3, V4> whenAllSucceed(
          ClosingFuture<V1> future1,
          ClosingFuture<V2> future2,
          ClosingFuture<V3> future3,
          ClosingFuture<V4> future4) {
    return new Combiner4<>(future1, future2, future3, future4);
  }

  /**
   * Starts specifying how to combine five {@link ClosingFuture}s into a single pipeline, assuming
   * they all succeed. If any fail, the resulting pipeline will fail.
   *
   * <p>Calling this method allows you to use lambdas or method references typed with the types of
   * the input {@link ClosingFuture}s.
   *
   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
   */
  public static <
          V1 extends @Nullable Object,
          V2 extends @Nullable Object,
          V3 extends @Nullable Object,
          V4 extends @Nullable Object,
          V5 extends @Nullable Object>
      Combiner5<V1, V2, V3, V4, V5> whenAllSucceed(
          ClosingFuture<V1> future1,
          ClosingFuture<V2> future2,
          ClosingFuture<V3> future3,
          ClosingFuture<V4> future4,
          ClosingFuture<V5> future5) {
    return new Combiner5<>(future1, future2, future3, future4, future5);
  }

  /**
   * Starts specifying how to combine {@link ClosingFuture}s into a single pipeline, assuming they
   * all succeed. If any fail, the resulting pipeline will fail.
   *
   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
   */
  public static Combiner whenAllSucceed(
      ClosingFuture<?> future1,
      ClosingFuture<?> future2,
      ClosingFuture<?> future3,
      ClosingFuture<?> future4,
      ClosingFuture<?> future5,
      ClosingFuture<?> future6,
      ClosingFuture<?>... moreFutures) {
    return whenAllSucceed(
        FluentIterable.of(future1, future2, future3, future4, future5, future6)
            .append(moreFutures));
  }

  private final AtomicReference<State> state = new AtomicReference<>(OPEN);
  private final CloseableList closeables = new CloseableList();
  private final FluentFuture<V> future;

  private ClosingFuture(ListenableFuture<V> future) {
    this.future = FluentFuture.from(future);
  }

  private ClosingFuture(final ClosingCallable<V> callable, Executor executor) {
    checkNotNull(callable);
    TrustedListenableFutureTask<V> task =
        TrustedListenableFutureTask.create(
            new Callable<V>() {
              @Override
              @ParametricNullness
              public V call() throws Exception {
                return callable.call(closeables.closer);
              }

              @Override
              public String toString() {
                return callable.toString();
              }
            });
    executor.execute(task);
    this.future = task;
  }

  private ClosingFuture(final AsyncClosingCallable<V> callable, Executor executor) {
    checkNotNull(callable);
    TrustedListenableFutureTask<V> task =
        TrustedListenableFutureTask.create(
            new AsyncCallable<V>() {
              @Override
              public ListenableFuture<V> call() throws Exception {
                CloseableList newCloseables = new CloseableList();
                try {
                  ClosingFuture<V> closingFuture = callable.call(newCloseables.closer);
                  closingFuture.becomeSubsumedInto(closeables);
                  return closingFuture.future;
                } finally {
                  closeables.add(newCloseables, directExecutor());
                }
              }

              @Override
              public String toString() {
                return callable.toString();
              }
            });
    executor.execute(task);
    this.future = task;
  }

  /**
   * Returns a future that finishes when this step does. Calling {@code get()} on the returned
   * future returns {@code null} if the step is successful or throws the same exception that would
   * be thrown by calling {@code finishToFuture().get()} if this were the last step. Calling {@code
   * cancel()} on the returned future has no effect on the {@code ClosingFuture} pipeline.
   *
   * <p>{@code statusFuture} differs from most methods on {@code ClosingFuture}: You can make calls
   * to {@code statusFuture} <i>in addition to</i> the call you make to {@link #finishToFuture()} or
   * a derivation method <i>on the same instance</i>. This is important because calling {@code
   * statusFuture} alone does not provide a way to close the pipeline.
   */
  public ListenableFuture<?> statusFuture() {
    return nonCancellationPropagating(future.transform(constant(null), directExecutor()));
  }

  /**
   * Returns a new {@code ClosingFuture} pipeline step derived from this one by applying a function
   * to its value. The function can use a {@link DeferredCloser} to capture objects to be closed
   * when the pipeline is done.
   *
   * <p>If this {@code ClosingFuture} fails, the function will not be called, and the derived {@code
   * ClosingFuture} will be equivalent to this one.
   *
   * <p>If the function throws an exception, that exception is used as the result of the derived
   * {@code ClosingFuture}.
   *
   * <p>Example usage:
   *
   * <pre>{@code
   * ClosingFuture<List<Row>> rowsFuture =
   *     queryFuture.transform((closer, result) -> result.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} documentation. All its warnings
   * about heavyweight listeners are also applicable to heavyweight functions passed to this method.
   *
   * <p>After calling this method, you may not call {@link #finishToFuture()}, {@link
   * #finishToValueAndCloser(ValueAndCloserConsumer, Executor)}, or any other derivation method on
   * the original {@code ClosingFuture} instance.
   *
   * @param function transforms the value of this step to the value of the derived step
   * @param executor executor to run the function in
   * @return the derived step
   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from this
   *     one, or if this {@code ClosingFuture} has already been {@linkplain #finishToFuture()
   *     finished}
   */
  public <U extends @Nullable Object> ClosingFuture<U> transform(
      final ClosingFunction<? super V, U> function, Executor executor) {
    checkNotNull(function);
    AsyncFunction<V, U> applyFunction =
        new AsyncFunction<V, U>() {
          @Override
          public ListenableFuture<U> apply(V input) throws Exception {
            return closeables.applyClosingFunction(function, input);
          }

          @Override
          public String toString() {
            return function.toString();
          }
        };
    // TODO(dpb): Switch to future.transformSync when that exists (passing a throwing function).
    return derive(future.transformAsync(applyFunction, executor));
  }

  /**
   * Returns a new {@code ClosingFuture} pipeline step derived from this one by applying a function
   * that returns a {@code ClosingFuture} to its value. The function can use a {@link
   * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
   * captured by the returned {@link ClosingFuture}).
   *
   * <p>If this {@code ClosingFuture} succeeds, the derived one will be equivalent to the one
   * returned by the function.
   *
   * <p>If this {@code ClosingFuture} fails, the function will not be called, and the derived {@code
   * ClosingFuture} will be equivalent to this one.
   *
   * <p>If the function throws an exception, that exception is used as the result of the derived
   * {@code ClosingFuture}. But if the exception is thrown after the function creates a {@code
   * ClosingFuture}, then none of the closeable objects in that {@code ClosingFuture} will be
   * closed.
   *
   * <p>Usage guidelines for this method:
   *
   * <ul>
   *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
   *       {@code ClosingFuture}. If possible, prefer calling {@link #transform(ClosingFunction,
   *       Executor)} instead, with a function that returns the next value directly.
   *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
   *       for every closeable object this step creates in order to capture it for later closing.
   *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
   *       ClosingFuture} call {@link #from(ListenableFuture)}.
   *   <li>In case this step doesn't create new closeables, you can adapt an API that returns a
   *       {@link ListenableFuture} to return a {@code ClosingFuture} by wrapping it with a call to
   *       {@link #withoutCloser(AsyncFunction)}
   * </ul>
   *
   * <p>Example usage:
   *
   * <pre>{@code
   * // Result.getRowsClosingFuture() returns a ClosingFuture.
   * ClosingFuture<List<Row>> rowsFuture =
   *     queryFuture.transformAsync((closer, result) -> result.getRowsClosingFuture(), executor);
   *
   * // Result.writeRowsToOutputStreamFuture() returns a ListenableFuture that resolves to the
   * // number of written rows. openOutputFile() returns a FileOutputStream (which implements
   * // Closeable).
   * ClosingFuture<Integer> rowsFuture2 =
   *     queryFuture.transformAsync(
   *         (closer, result) -> {
   *           FileOutputStream fos = closer.eventuallyClose(openOutputFile(), closingExecutor);
   *           return ClosingFuture.from(result.writeRowsToOutputStreamFuture(fos));
   *      },
   *      executor);
   *
   * // Result.getRowsFuture() returns a ListenableFuture (no new closeables are created).
   * ClosingFuture<List<Row>> rowsFuture3 =
   *     queryFuture.transformAsync(withoutCloser(Result::getRowsFuture), executor);
   *
   * }</pre>
   *
   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
   * the discussion in the {@link 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 AsyncClosingFunction.apply}. Any heavyweight operations should occur in other threads
   * responsible for completing the returned {@code ClosingFuture}.)
   *
   * <p>After calling this method, you may not call {@link #finishToFuture()}, {@link
   * #finishToValueAndCloser(ValueAndCloserConsumer, Executor)}, or any other derivation method on
   * the original {@code ClosingFuture} instance.
   *
   * @param function transforms the value of this step to a {@code ClosingFuture} with the value of
   *     the derived step
   * @param executor executor to run the function in
   * @return the derived step
   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from this
   *     one, or if this {@code ClosingFuture} has already been {@linkplain #finishToFuture()
   *     finished}
   */
  public <U extends @Nullable Object> ClosingFuture<U> transformAsync(
      final AsyncClosingFunction<? super V, U> function, Executor executor) {
    checkNotNull(function);
    AsyncFunction<V, U> applyFunction =
        new AsyncFunction<V, U>() {
          @Override
          public ListenableFuture<U> apply(V input) throws Exception {
            return closeables.applyAsyncClosingFunction(function, input);
          }

          @Override
          public String toString() {
            return function.toString();
          }
        };
    return derive(future.transformAsync(applyFunction, executor));
  }

  /**
   * Returns an {@link AsyncClosingFunction} that applies an {@link AsyncFunction} to an input,
   * ignoring the DeferredCloser and returning a {@code ClosingFuture} derived from the returned
   * {@link ListenableFuture}.
   *
   * <p>Use this method to pass a transformation to {@link #transformAsync(AsyncClosingFunction,
   * Executor)} or to {@link #catchingAsync(Class, AsyncClosingFunction, Executor)} as long as it
   * meets these conditions:
   *
   * <ul>
   *   <li>It does not need to capture any {@link Closeable} objects by calling {@link
   *       DeferredCloser#eventuallyClose(Object, Executor)}.
   *   <li>It returns a {@link ListenableFuture}.
   * </ul>
   *
   * <p>Example usage:
   *
   * <pre>{@code
   * // Result.getRowsFuture() returns a ListenableFuture.
   * ClosingFuture<List<Row>> rowsFuture =
   *     queryFuture.transformAsync(withoutCloser(Result::getRowsFuture), executor);
   * }</pre>
   *
   * @param function transforms the value of a {@code ClosingFuture} step to a {@link
   *     ListenableFuture} with the value of a derived step
   */
  public static <V extends @Nullable Object, U extends @Nullable Object>
      AsyncClosingFunction<V, U> withoutCloser(final AsyncFunction<V, U> function) {
    checkNotNull(function);
    return new AsyncClosingFunction<V, U>() {
      @Override
      public ClosingFuture<U> apply(DeferredCloser closer, V input) throws Exception {
        return ClosingFuture.from(function.apply(input));
      }
    };
  }

  /**
   * Returns a new {@code ClosingFuture} pipeline step derived from this one by applying a function
   * to its exception if it is an instance of a given exception type. The function can use a {@link
   * DeferredCloser} to capture objects to be closed when the pipeline is done.
   *
   * <p>If this {@code ClosingFuture} succeeds or fails with a different exception type, the
   * function will not be called, and the derived {@code ClosingFuture} will be equivalent to this
   * one.
   *
   * <p>If the function throws an exception, that exception is used as the result of the derived
   * {@code ClosingFuture}.
   *
   * <p>Example usage:
   *
   * <pre>{@code
   * ClosingFuture<QueryResult> queryFuture =
   *     queryFuture.catching(
   *         QueryException.class, (closer, x) -> Query.emptyQueryResult(), executor);
   * }</pre>
   *
   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
   * the discussion in the {@link ListenableFuture#addListener} documentation. All its warnings
   * about heavyweight listeners are also applicable to heavyweight functions passed to this method.
   *
   * <p>After calling this method, you may not call {@link #finishToFuture()}, {@link
   * #finishToValueAndCloser(ValueAndCloserConsumer, Executor)}, or any other derivation method on
   * the original {@code ClosingFuture} instance.
   *
   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
   *     type is matched against this step's exception. "This step's exception" means the cause of
   *     the {@link ExecutionException} thrown by {@link Future#get()} on the {@link Future}
   *     underlying this step 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 function to be called if this step fails with the expected exception type.
   *     The function's argument is this step's exception. "This step's exception" means the cause
   *     of the {@link ExecutionException} thrown by {@link Future#get()} on the {@link Future}
   *     underlying this step or, if {@code get()} throws a different kind of exception, that
   *     exception itself.
   * @param executor the executor that runs {@code fallback} if the input fails
   */
  public <X extends Throwable> ClosingFuture<V> catching(
      Class<X> exceptionType, ClosingFunction<? super X, ? extends V> fallback, Executor executor) {
    return catchingMoreGeneric(exceptionType, fallback, executor);
  }

  // Avoids generic type capture inconsistency problems where |? extends V| is incompatible with V.
  private <X extends Throwable, W extends V> ClosingFuture<V> catchingMoreGeneric(
      Class<X> exceptionType, final ClosingFunction<? super X, W> fallback, Executor executor) {
    checkNotNull(fallback);
    AsyncFunction<X, W> applyFallback =
        new AsyncFunction<X, W>() {
          @Override
          public ListenableFuture<W> apply(X exception) throws Exception {
            return closeables.applyClosingFunction(fallback, exception);
          }

          @Override
          public String toString() {
            return fallback.toString();
          }
        };
    // TODO(dpb): Switch to future.catchingSync when that exists (passing a throwing function).
    return derive(future.catchingAsync(exceptionType, applyFallback, executor));
  }

  /**
   * Returns a new {@code ClosingFuture} pipeline step derived from this one by applying a function
   * that returns a {@code ClosingFuture} to its exception if it is an instance of a given exception
   * type. The function can use a {@link DeferredCloser} to capture objects to be closed when the
   * pipeline is done (other than those captured by the returned {@link ClosingFuture}).
   *
   * <p>If this {@code ClosingFuture} fails with an exception of the given type, the derived {@code
   * ClosingFuture} will be equivalent to the one returned by the function.
   *
   * <p>If this {@code ClosingFuture} succeeds or fails with a different exception type, the
   * function will not be called, and the derived {@code ClosingFuture} will be equivalent to this
   * one.
   *
   * <p>If the function throws an exception, that exception is used as the result of the derived
   * {@code ClosingFuture}. But if the exception is thrown after the function creates a {@code
   * ClosingFuture}, then none of the closeable objects in that {@code ClosingFuture} will be
   * closed.
   *
   * <p>Usage guidelines for this method:
   *
   * <ul>
   *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
   *       {@code ClosingFuture}. If possible, prefer calling {@link #catching(Class,
   *       ClosingFunction, Executor)} instead, with a function that returns the next value
   *       directly.
   *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
   *       for every closeable object this step creates in order to capture it for later closing.
   *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
   *       ClosingFuture} call {@link #from(ListenableFuture)}.
   *   <li>In case this step doesn't create new closeables, you can adapt an API that returns a
   *       {@link ListenableFuture} to return a {@code ClosingFuture} by wrapping it with a call to
   *       {@link #withoutCloser(AsyncFunction)}
   * </ul>
   *
   * <p>Example usage:
   *
   * <pre>{@code
   * // Fall back to a secondary input stream in case of IOException.
   * ClosingFuture<InputStream> inputFuture =
   *     firstInputFuture.catchingAsync(
   *         IOException.class, (closer, x) -> secondaryInputStreamClosingFuture(), executor);
   * }
   * }</pre>
   *
   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
   * the discussion in the {@link 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 AsyncClosingFunction.apply}. Any heavyweight operations should occur in other threads
   * responsible for completing the returned {@code ClosingFuture}.)
   *
   * <p>After calling this method, you may not call {@link #finishToFuture()}, {@link
   * #finishToValueAndCloser(ValueAndCloserConsumer, Executor)}, or any other derivation method on
   * the original {@code ClosingFuture} instance.
   *
   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
   *     type is matched against this step's exception. "This step's exception" means the cause of
   *     the {@link ExecutionException} thrown by {@link Future#get()} on the {@link Future}
   *     underlying this step 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 function to be called if this step fails with the expected exception type.
   *     The function's argument is this step's exception. "This step's exception" means the cause
   *     of the {@link ExecutionException} thrown by {@link Future#get()} on the {@link Future}
   *     underlying this step or, if {@code get()} throws a different kind of exception, that
   *     exception itself.
   * @param executor the executor that runs {@code fallback} if the input fails
   */
  // TODO(dpb): Should this do something special if the function throws CancellationException or
  // ExecutionException?
  public <X extends Throwable> ClosingFuture<V> catchingAsync(
      Class<X> exceptionType,
      AsyncClosingFunction<? super X, ? extends V> fallback,
      Executor executor) {
    return catchingAsyncMoreGeneric(exceptionType, fallback, executor);
  }

  // Avoids generic type capture inconsistency problems where |? extends V| is incompatible with V.
  private <X extends Throwable, W extends V> ClosingFuture<V> catchingAsyncMoreGeneric(
      Class<X> exceptionType,
      final AsyncClosingFunction<? super X, W> fallback,
      Executor executor) {
    checkNotNull(fallback);
    AsyncFunction<X, W> asyncFunction =
        new AsyncFunction<X, W>() {
          @Override
          public ListenableFuture<W> apply(X exception) throws Exception {
            return closeables.applyAsyncClosingFunction(fallback, exception);
          }

          @Override
          public String toString() {
            return fallback.toString();
          }
        };
    return derive(future.catchingAsync(exceptionType, asyncFunction, executor));
  }

  /**
   * Marks this step as the last step in the {@code ClosingFuture} pipeline.
   *
   * <p>The returned {@link Future} is completed when the pipeline's computation completes, or when
   * the pipeline is cancelled.
   *
   * <p>All objects the pipeline has captured for closing will begin to be closed asynchronously
   * <b>after</b> the returned {@code Future} is done: the future completes before closing starts,
   * rather than once it has finished.
   *
   * <p>After calling this method, you may not call {@link
   * #finishToValueAndCloser(ValueAndCloserConsumer, Executor)}, this method, or any other
   * derivation method on the original {@code ClosingFuture} instance.
   *
   * @return a {@link Future} that represents the final value or exception of the pipeline
   */
  public FluentFuture<V> finishToFuture() {
    if (compareAndUpdateState(OPEN, WILL_CLOSE)) {
      logger.get().log(FINER, "will close {0}", this);
      future.addListener(
          new Runnable() {
            @Override
            public void run() {
              checkAndUpdateState(WILL_CLOSE, CLOSING);
              close();
              checkAndUpdateState(CLOSING, CLOSED);
            }
          },
          directExecutor());
    } else {
      switch (state.get()) {
        case SUBSUMED:
          throw new IllegalStateException(
              "Cannot call finishToFuture() after deriving another step");

        case WILL_CREATE_VALUE_AND_CLOSER:
          throw new IllegalStateException(
              "Cannot call finishToFuture() after calling finishToValueAndCloser()");

        case WILL_CLOSE:
        case CLOSING:
        case CLOSED:
          throw new IllegalStateException("Cannot call finishToFuture() twice");

        case OPEN:
          throw new AssertionError();
      }
    }
    return future;
  }

  /**
   * Marks this step as the last step in the {@code ClosingFuture} pipeline. When this step is done,
   * {@code receiver} will be called with an object that contains the result of the operation. The
   * receiver can store the {@link ValueAndCloser} outside the receiver for later synchronous use.
   *
   * <p>After calling this method, you may not call {@link #finishToFuture()}, this method again, or
   * any other derivation method on the original {@code ClosingFuture} instance.
   *
   * @param consumer a callback whose method will be called (using {@code executor}) when this
   *     operation is done
   */
  public void finishToValueAndCloser(
      final ValueAndCloserConsumer<? super V> consumer, Executor executor) {
    checkNotNull(consumer);
    if (!compareAndUpdateState(OPEN, WILL_CREATE_VALUE_AND_CLOSER)) {
      switch (state.get()) {
        case SUBSUMED:
          throw new IllegalStateException(
              "Cannot call finishToValueAndCloser() after deriving another step");

        case WILL_CLOSE:
        case CLOSING:
        case CLOSED:
          throw new IllegalStateException(
              "Cannot call finishToValueAndCloser() after calling finishToFuture()");

        case WILL_CREATE_VALUE_AND_CLOSER:
          throw new IllegalStateException("Cannot call finishToValueAndCloser() twice");

        case OPEN:
          break;
      }
      throw new AssertionError(state);
    }
    future.addListener(
        new Runnable() {
          @Override
          public void run() {
            provideValueAndCloser(consumer, ClosingFuture.this);
          }
        },
        executor);
  }

  private static <C extends @Nullable Object, V extends C> void provideValueAndCloser(
      ValueAndCloserConsumer<C> consumer, ClosingFuture<V> closingFuture) {
    consumer.accept(new ValueAndCloser<C>(closingFuture));
  }

  /**
   * Attempts to cancel execution of this step. This attempt will fail if the step has already
   * completed, has already been cancelled, or could not be cancelled for some other reason. If
   * successful, and this step has not started when {@code cancel} is called, this step should never
   * run.
   *
   * <p>If successful, causes the objects captured by this step (if already started) and its input
   * step(s) for later closing to be closed on their respective {@link Executor}s. If any such calls
   * specified {@link MoreExecutors#directExecutor()}, those objects will be closed synchronously.
   *
   * @param mayInterruptIfRunning {@code true} if the thread executing this task should be
   *     interrupted; otherwise, in-progress tasks are allowed to complete, but the step will be
   *     cancelled regardless
   * @return {@code false} if the step could not be cancelled, typically because it has already
   *     completed normally; {@code true} otherwise
   */
  @CanIgnoreReturnValue
  public boolean cancel(boolean mayInterruptIfRunning) {
    logger.get().log(FINER, "cancelling {0}", this);
    boolean cancelled = future.cancel(mayInterruptIfRunning);
    if (cancelled) {
      close();
    }
    return cancelled;
  }

  private void close() {
    logger.get().log(FINER, "closing {0}", this);
    closeables.close();
  }

  private <U extends @Nullable Object> ClosingFuture<U> derive(FluentFuture<U> future) {
    ClosingFuture<U> derived = new ClosingFuture<>(future);
    becomeSubsumedInto(derived.closeables);
    return derived;
  }

  private void becomeSubsumedInto(CloseableList otherCloseables) {
    checkAndUpdateState(OPEN, SUBSUMED);
    otherCloseables.add(closeables, directExecutor());
  }

  /**
   * An object that can return the value of the {@link ClosingFuture}s that are passed to {@link
   * #whenAllComplete(Iterable)} or {@link #whenAllSucceed(Iterable)}.
   *
   * <p>Only for use by a {@link CombiningCallable} or {@link AsyncCombiningCallable} object.
   */
  public static final class Peeker {
    private final ImmutableList<ClosingFuture<?>> futures;
    private volatile boolean beingCalled;

    private Peeker(ImmutableList<ClosingFuture<?>> futures) {
      this.futures = checkNotNull(futures);
    }

    /**
     * Returns the value of {@code closingFuture}.
     *
     * @throws ExecutionException if {@code closingFuture} is a failed step
     * @throws CancellationException if the {@code closingFuture}'s future was cancelled
     * @throws IllegalArgumentException if {@code closingFuture} is not one of the futures passed to
     *     {@link #whenAllComplete(Iterable)} or {@link #whenAllComplete(Iterable)}
     * @throws IllegalStateException if called outside of a call to {@link
     *     CombiningCallable#call(DeferredCloser, Peeker)} or {@link
     *     AsyncCombiningCallable#call(DeferredCloser, Peeker)}
     */
    @ParametricNullness
    public final <D extends @Nullable Object> D getDone(ClosingFuture<D> closingFuture)
        throws ExecutionException {
      checkState(beingCalled);
      checkArgument(futures.contains(closingFuture));
      return Futures.getDone(closingFuture.future);
    }

    @ParametricNullness
    private <V extends @Nullable Object> V call(
        CombiningCallable<V> combiner, CloseableList closeables) throws Exception {
      beingCalled = true;
      CloseableList newCloseables = new CloseableList();
      try {
        return combiner.call(newCloseables.closer, this);
      } finally {
        closeables.add(newCloseables, directExecutor());
        beingCalled = false;
      }
    }

    private <V extends @Nullable Object> FluentFuture<V> callAsync(
        AsyncCombiningCallable<V> combiner, CloseableList closeables) throws Exception {
      beingCalled = true;
      CloseableList newCloseables = new CloseableList();
      try {
        ClosingFuture<V> closingFuture = combiner.call(newCloseables.closer, this);
        closingFuture.becomeSubsumedInto(closeables);
        return closingFuture.future;
      } finally {
        closeables.add(newCloseables, directExecutor());
        beingCalled = false;
      }
    }
  }

  /**
   * A builder of a {@link ClosingFuture} step that is derived from more than one input step.
   *
   * <p>See {@link #whenAllComplete(Iterable)} and {@link #whenAllSucceed(Iterable)} for how to
   * instantiate this class.
   *
   * <p>Example:
   *
   * <pre>{@code
   * final ClosingFuture<BufferedReader> file1ReaderFuture = ...;
   * final ClosingFuture<BufferedReader> file2ReaderFuture = ...;
   * ListenableFuture<Integer> numberOfDifferentLines =
   *       ClosingFuture.whenAllSucceed(file1ReaderFuture, file2ReaderFuture)
   *           .call(
   *               (closer, peeker) -> {
   *                 BufferedReader file1Reader = peeker.getDone(file1ReaderFuture);
   *                 BufferedReader file2Reader = peeker.getDone(file2ReaderFuture);
   *                 return countDifferentLines(file1Reader, file2Reader);
   *               },
   *               executor)
   *           .closing(executor);
   * }</pre>
   */
  // TODO(cpovirk): Use simple name instead of fully qualified after we stop building with JDK 8.
  @com.google.errorprone.annotations.DoNotMock(
      "Use ClosingFuture.whenAllSucceed() or .whenAllComplete() instead.")
  public static class Combiner {

    private final CloseableList closeables = new CloseableList();

    /**
     * An operation that returns a result and may throw an exception.
     *
     * @param <V> the type of the result
     */
    @FunctionalInterface
    public interface CombiningCallable<V extends @Nullable Object> {
      /**
       * Computes a result, or throws an exception if unable to do so.
       *
       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
       * (but not before this method completes), even if this method throws or the pipeline is
       * cancelled.
       *
       * @param peeker used to get the value of any of the input futures
       */
      @ParametricNullness
      V call(DeferredCloser closer, Peeker peeker) throws Exception;
    }

    /**
     * An operation that returns a {@link ClosingFuture} result and may throw an exception.
     *
     * @param <V> the type of the result
     */
    @FunctionalInterface
    public interface AsyncCombiningCallable<V extends @Nullable Object> {
      /**
       * Computes a {@link ClosingFuture} result, or throws an exception if unable to do so.
       *
       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
       * (but not before this method completes), even if this method throws or the pipeline is
       * cancelled.
       *
       * @param peeker used to get the value of any of the input futures
       */
      ClosingFuture<V> call(DeferredCloser closer, Peeker peeker) throws Exception;
    }

    private final boolean allMustSucceed;
    protected final ImmutableList<ClosingFuture<?>> inputs;

    private Combiner(boolean allMustSucceed, Iterable<? extends ClosingFuture<?>> inputs) {
      this.allMustSucceed = allMustSucceed;
      this.inputs = ImmutableList.copyOf(inputs);
      for (ClosingFuture<?> input : inputs) {
        input.becomeSubsumedInto(closeables);
      }
    }

    /**
     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
     * combining function to their values. The function can use a {@link DeferredCloser} to capture
     * objects to be closed when the pipeline is done.
     *
     * <p>If this combiner was returned by a {@link #whenAllSucceed} method and any of the inputs
     * fail, so will the returned step.
     *
     * <p>If the combiningCallable throws a {@code CancellationException}, the pipeline will be
     * cancelled.
     *
     * <p>If the combiningCallable throws an {@code ExecutionException}, the cause of the thrown
     * {@code ExecutionException} will be extracted and used as the failure of the derived step.
     */
    public <V extends @Nullable Object> ClosingFuture<V> call(
        final CombiningCallable<V> combiningCallable, Executor executor) {
      Callable<V> callable =
          new Callable<V>() {
            @Override
            @ParametricNullness
            public V call() throws Exception {
              return new Peeker(inputs).call(combiningCallable, closeables);
            }

            @Override
            public String toString() {
              return combiningCallable.toString();
            }
          };
      ClosingFuture<V> derived = new ClosingFuture<>(futureCombiner().call(callable, executor));
      derived.closeables.add(closeables, directExecutor());
      return derived;
    }

    /**
     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
     * {@code ClosingFuture}-returning function to their values. The function can use a {@link
     * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
     * captured by the returned {@link ClosingFuture}).
     *
     * <p>If this combiner was returned by a {@link #whenAllSucceed} method and any of the inputs
     * fail, so will the returned step.
     *
     * <p>If the combiningCallable throws a {@code CancellationException}, the pipeline will be
     * cancelled.
     *
     * <p>If the combiningCallable throws an {@code ExecutionException}, the cause of the thrown
     * {@code ExecutionException} will be extracted and used as the failure of the derived step.
     *
     * <p>If the combiningCallable throws any other exception, it will be used as the failure of the
     * derived step.
     *
     * <p>If an exception is thrown after the combiningCallable creates a {@code ClosingFuture},
     * then none of the closeable objects in that {@code ClosingFuture} will be closed.
     *
     * <p>Usage guidelines for this method:
     *
     * <ul>
     *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
     *       {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
     *       Executor)} instead, with a function that returns the next value directly.
     *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
     *       for every closeable object this step creates in order to capture it for later closing.
     *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
     *       ClosingFuture} call {@link #from(ListenableFuture)}.
     * </ul>
     *
     * <p>The same warnings about doing heavyweight operations within {@link
     * ClosingFuture#transformAsync(AsyncClosingFunction, Executor)} apply here.
     */
    public <V extends @Nullable Object> ClosingFuture<V> callAsync(
        final AsyncCombiningCallable<V> combiningCallable, Executor executor) {
      AsyncCallable<V> asyncCallable =
          new AsyncCallable<V>() {
            @Override
            public ListenableFuture<V> call() throws Exception {
              return new Peeker(inputs).callAsync(combiningCallable, closeables);
            }

            @Override
            public String toString() {
              return combiningCallable.toString();
            }
          };
      ClosingFuture<V> derived =
          new ClosingFuture<>(futureCombiner().callAsync(asyncCallable, executor));
      derived.closeables.add(closeables, directExecutor());
      return derived;
    }

    private FutureCombiner<@Nullable Object> futureCombiner() {
      return allMustSucceed
          ? Futures.whenAllSucceed(inputFutures())
          : Futures.whenAllComplete(inputFutures());
    }


    private ImmutableList<FluentFuture<?>> inputFutures() {
      return FluentIterable.from(inputs)
          .<FluentFuture<?>>transform(future -> future.future)
          .toList();
    }
  }

  /**
   * A generic {@link Combiner} that lets you use a lambda or method reference to combine two {@link
   * ClosingFuture}s. Use {@link #whenAllSucceed(ClosingFuture, ClosingFuture)} to start this
   * combination.
   *
   * @param <V1> the type returned by the first future
   * @param <V2> the type returned by the second future
   */
  public static final class Combiner2<V1 extends @Nullable Object, V2 extends @Nullable Object>
      extends Combiner {

    /**
     * A function that returns a value when applied to the values of the two futures passed to
     * {@link #whenAllSucceed(ClosingFuture, ClosingFuture)}.
     *
     * @param <V1> the type returned by the first future
     * @param <V2> the type returned by the second future
     * @param <U> the type returned by the function
     */
    @FunctionalInterface
    public interface ClosingFunction2<
        V1 extends @Nullable Object, V2 extends @Nullable Object, U extends @Nullable Object> {

      /**
       * Applies this function to two inputs, or throws an exception if unable to do so.
       *
       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
       * (but not before this method completes), even if this method throws or the pipeline is
       * cancelled.
       */
      @ParametricNullness
      U apply(DeferredCloser closer, @ParametricNullness V1 value1, @ParametricNullness V2 value2)
          throws Exception;
    }

    /**
     * A function that returns a {@link ClosingFuture} when applied to the values of the two futures
     * passed to {@link #whenAllSucceed(ClosingFuture, ClosingFuture)}.
     *
     * @param <V1> the type returned by the first future
     * @param <V2> the type returned by the second future
     * @param <U> the type returned by the function
     */
    @FunctionalInterface
    public interface AsyncClosingFunction2<
        V1 extends @Nullable Object, V2 extends @Nullable Object, U extends @Nullable Object> {

      /**
       * Applies this function to two inputs, or throws an exception if unable to do so.
       *
       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
       * (but not before this method completes), even if this method throws or the pipeline is
       * cancelled.
       */
      ClosingFuture<U> apply(
          DeferredCloser closer, @ParametricNullness V1 value1, @ParametricNullness V2 value2)
          throws Exception;
    }

    private final ClosingFuture<V1> future1;
    private final ClosingFuture<V2> future2;

    private Combiner2(ClosingFuture<V1> future1, ClosingFuture<V2> future2) {
      super(true, ImmutableList.of(future1, future2));
      this.future1 = future1;
      this.future2 = future2;
    }

    /**
     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
     * combining function to their values. The function can use a {@link DeferredCloser} to capture
     * objects to be closed when the pipeline is done.
     *
     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture)} and
     * any of the inputs fail, so will the returned step.
     *
     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
     *
     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
     * ExecutionException} will be extracted and used as the failure of the derived step.
     */
    public <U extends @Nullable Object> ClosingFuture<U> call(
        final ClosingFunction2<V1, V2, U> function, Executor executor) {
      return call(
          new CombiningCallable<U>() {
            @Override
            @ParametricNullness
            public U call(DeferredCloser closer, Peeker peeker) throws Exception {
              return function.apply(closer, peeker.getDone(future1), peeker.getDone(future2));
            }

            @Override
            public String toString() {
              return function.toString();
            }
          },
          executor);
    }

    /**
     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
     * {@code ClosingFuture}-returning function to their values. The function can use a {@link
     * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
     * captured by the returned {@link ClosingFuture}).
     *
     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture)} and
     * any of the inputs fail, so will the returned step.
     *
     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
     *
     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
     * ExecutionException} will be extracted and used as the failure of the derived step.
     *
     * <p>If the function throws any other exception, it will be used as the failure of the derived
     * step.
     *
     * <p>If an exception is thrown after the function creates a {@code ClosingFuture}, then none of
     * the closeable objects in that {@code ClosingFuture} will be closed.
     *
     * <p>Usage guidelines for this method:
     *
     * <ul>
     *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
     *       {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
     *       Executor)} instead, with a function that returns the next value directly.
     *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
     *       for every closeable object this step creates in order to capture it for later closing.
     *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
     *       ClosingFuture} call {@link #from(ListenableFuture)}.
     * </ul>
     *
     * <p>The same warnings about doing heavyweight operations within {@link
     * ClosingFuture#transformAsync(AsyncClosingFunction, Executor)} apply here.
     */
    public <U extends @Nullable Object> ClosingFuture<U> callAsync(
        final AsyncClosingFunction2<V1, V2, U> function, Executor executor) {
      return callAsync(
          new AsyncCombiningCallable<U>() {
            @Override
            public ClosingFuture<U> call(DeferredCloser closer, Peeker peeker) throws Exception {
              return function.apply(closer, peeker.getDone(future1), peeker.getDone(future2));
            }

            @Override
            public String toString() {
              return function.toString();
            }
          },
          executor);
    }
  }

  /**
   * A generic {@link Combiner} that lets you use a lambda or method reference to combine three
   * {@link ClosingFuture}s. Use {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
   * ClosingFuture)} to start this combination.
   *
   * @param <V1> the type returned by the first future
   * @param <V2> the type returned by the second future
   * @param <V3> the type returned by the third future
   */
  public static final class Combiner3<
          V1 extends @Nullable Object, V2 extends @Nullable Object, V3 extends @Nullable Object>
      extends Combiner {
    /**
     * A function that returns a value when applied to the values of the three futures passed to
     * {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture)}.
     *
     * @param <V1> the type returned by the first future
     * @param <V2> the type returned by the second future
     * @param <V3> the type returned by the third future
     * @param <U> the type returned by the function
     */
    @FunctionalInterface
    public interface ClosingFunction3<
        V1 extends @Nullable Object,
        V2 extends @Nullable Object,
        V3 extends @Nullable Object,
        U extends @Nullable Object> {
      /**
       * Applies this function to three inputs, or throws an exception if unable to do so.
       *
       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
       * (but not before this method completes), even if this method throws or the pipeline is
       * cancelled.
       */
      @ParametricNullness
      U apply(
          DeferredCloser closer,
          @ParametricNullness V1 value1,
          @ParametricNullness V2 value2,
          @ParametricNullness V3 value3)
          throws Exception;
    }

    /**
     * A function that returns a {@link ClosingFuture} when applied to the values of the three
     * futures passed to {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture)}.
     *
     * @param <V1> the type returned by the first future
     * @param <V2> the type returned by the second future
     * @param <V3> the type returned by the third future
     * @param <U> the type returned by the function
     */
    @FunctionalInterface
    public interface AsyncClosingFunction3<
        V1 extends @Nullable Object,
        V2 extends @Nullable Object,
        V3 extends @Nullable Object,
        U extends @Nullable Object> {
      /**
       * Applies this function to three inputs, or throws an exception if unable to do so.
       *
       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
       * (but not before this method completes), even if this method throws or the pipeline is
       * cancelled.
       */
      ClosingFuture<U> apply(
          DeferredCloser closer,
          @ParametricNullness V1 value1,
          @ParametricNullness V2 value2,
          @ParametricNullness V3 value3)
          throws Exception;
    }

    private final ClosingFuture<V1> future1;
    private final ClosingFuture<V2> future2;
    private final ClosingFuture<V3> future3;

    private Combiner3(
        ClosingFuture<V1> future1, ClosingFuture<V2> future2, ClosingFuture<V3> future3) {
      super(true, ImmutableList.of(future1, future2, future3));
      this.future1 = future1;
      this.future2 = future2;
      this.future3 = future3;
    }

    /**
     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
     * combining function to their values. The function can use a {@link DeferredCloser} to capture
     * objects to be closed when the pipeline is done.
     *
     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
     * ClosingFuture)} and any of the inputs fail, so will the returned step.
     *
     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
     *
     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
     * ExecutionException} will be extracted and used as the failure of the derived step.
     */
    public <U extends @Nullable Object> ClosingFuture<U> call(
        final ClosingFunction3<V1, V2, V3, U> function, Executor executor) {
      return call(
          new CombiningCallable<U>() {
            @Override
            @ParametricNullness
            public U call(DeferredCloser closer, Peeker peeker) throws Exception {
              return function.apply(
                  closer,
                  peeker.getDone(future1),
                  peeker.getDone(future2),
                  peeker.getDone(future3));
            }

            @Override
            public String toString() {
              return function.toString();
            }
          },
          executor);
    }

    /**
     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
     * {@code ClosingFuture}-returning function to their values. The function can use a {@link
     * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
     * captured by the returned {@link ClosingFuture}).
     *
     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
     * ClosingFuture)} and any of the inputs fail, so will the returned step.
     *
     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
     *
     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
     * ExecutionException} will be extracted and used as the failure of the derived step.
     *
     * <p>If the function throws any other exception, it will be used as the failure of the derived
     * step.
     *
     * <p>If an exception is thrown after the function creates a {@code ClosingFuture}, then none of
     * the closeable objects in that {@code ClosingFuture} will be closed.
     *
     * <p>Usage guidelines for this method:
     *
     * <ul>
     *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
     *       {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
     *       Executor)} instead, with a function that returns the next value directly.
     *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
     *       for every closeable object this step creates in order to capture it for later closing.
     *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
     *       ClosingFuture} call {@link #from(ListenableFuture)}.
     * </ul>
     *
     * <p>The same warnings about doing heavyweight operations within {@link
     * ClosingFuture#transformAsync(AsyncClosingFunction, Executor)} apply here.
     */
    public <U extends @Nullable Object> ClosingFuture<U> callAsync(
        final AsyncClosingFunction3<V1, V2, V3, U> function, Executor executor) {
      return callAsync(
          new AsyncCombiningCallable<U>() {
            @Override
            public ClosingFuture<U> call(DeferredCloser closer, Peeker peeker) throws Exception {
              return function.apply(
                  closer,
                  peeker.getDone(future1),
                  peeker.getDone(future2),
                  peeker.getDone(future3));
            }

            @Override
            public String toString() {
              return function.toString();
            }
          },
          executor);
    }
  }

  /**
   * A generic {@link Combiner} that lets you use a lambda or method reference to combine four
   * {@link ClosingFuture}s. Use {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture,
   * ClosingFuture)} to start this combination.
   *
   * @param <V1> the type returned by the first future
   * @param <V2> the type returned by the second future
   * @param <V3> the type returned by the third future
   * @param <V4> the type returned by the fourth future
   */
  public static final class Combiner4<
          V1 extends @Nullable Object,
          V2 extends @Nullable Object,
          V3 extends @Nullable Object,
          V4 extends @Nullable Object>
      extends Combiner {
    /**
     * A function that returns a value when applied to the values of the four futures passed to
     * {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture, ClosingFuture)}.
     *
     * @param <V1> the type returned by the first future
     * @param <V2> the type returned by the second future
     * @param <V3> the type returned by the third future
     * @param <V4> the type returned by the fourth future
     * @param <U> the type returned by the function
     */
    @FunctionalInterface
    public interface ClosingFunction4<
        V1 extends @Nullable Object,
        V2 extends @Nullable Object,
        V3 extends @Nullable Object,
        V4 extends @Nullable Object,
        U extends @Nullable Object> {
      /**
       * Applies this function to four inputs, or throws an exception if unable to do so.
       *
       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
       * (but not before this method completes), even if this method throws or the pipeline is
       * cancelled.
       */
      @ParametricNullness
      U apply(
          DeferredCloser closer,
          @ParametricNullness V1 value1,
          @ParametricNullness V2 value2,
          @ParametricNullness V3 value3,
          @ParametricNullness V4 value4)
          throws Exception;
    }

    /**
     * A function that returns a {@link ClosingFuture} when applied to the values of the four
     * futures passed to {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture,
     * ClosingFuture)}.
     *
     * @param <V1> the type returned by the first future
     * @param <V2> the type returned by the second future
     * @param <V3> the type returned by the third future
     * @param <V4> the type returned by the fourth future
     * @param <U> the type returned by the function
     */
    @FunctionalInterface
    public interface AsyncClosingFunction4<
        V1 extends @Nullable Object,
        V2 extends @Nullable Object,
        V3 extends @Nullable Object,
        V4 extends @Nullable Object,
        U extends @Nullable Object> {
      /**
       * Applies this function to four inputs, or throws an exception if unable to do so.
       *
       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
       * (but not before this method completes), even if this method throws or the pipeline is
       * cancelled.
       */
      ClosingFuture<U> apply(
          DeferredCloser closer,
          @ParametricNullness V1 value1,
          @ParametricNullness V2 value2,
          @ParametricNullness V3 value3,
          @ParametricNullness V4 value4)
          throws Exception;
    }

    private final ClosingFuture<V1> future1;
    private final ClosingFuture<V2> future2;
    private final ClosingFuture<V3> future3;
    private final ClosingFuture<V4> future4;

    private Combiner4(
        ClosingFuture<V1> future1,
        ClosingFuture<V2> future2,
        ClosingFuture<V3> future3,
        ClosingFuture<V4> future4) {
      super(true, ImmutableList.of(future1, future2, future3, future4));
      this.future1 = future1;
      this.future2 = future2;
      this.future3 = future3;
      this.future4 = future4;
    }

    /**
     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
     * combining function to their values. The function can use a {@link DeferredCloser} to capture
     * objects to be closed when the pipeline is done.
     *
     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
     * ClosingFuture, ClosingFuture)} and any of the inputs fail, so will the returned step.
     *
     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
     *
     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
     * ExecutionException} will be extracted and used as the failure of the derived step.
     */
    public <U extends @Nullable Object> ClosingFuture<U> call(
        final ClosingFunction4<V1, V2, V3, V4, U> function, Executor executor) {
      return call(
          new CombiningCallable<U>() {
            @Override
            @ParametricNullness
            public U call(DeferredCloser closer, Peeker peeker) throws Exception {
              return function.apply(
                  closer,
                  peeker.getDone(future1),
                  peeker.getDone(future2),
                  peeker.getDone(future3),
                  peeker.getDone(future4));
            }

            @Override
            public String toString() {
              return function.toString();
            }
          },
          executor);
    }

    /**
     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
     * {@code ClosingFuture}-returning function to their values. The function can use a {@link
     * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
     * captured by the returned {@link ClosingFuture}).
     *
     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
     * ClosingFuture, ClosingFuture)} and any of the inputs fail, so will the returned step.
     *
     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
     *
     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
     * ExecutionException} will be extracted and used as the failure of the derived step.
     *
     * <p>If the function throws any other exception, it will be used as the failure of the derived
     * step.
     *
     * <p>If an exception is thrown after the function creates a {@code ClosingFuture}, then none of
     * the closeable objects in that {@code ClosingFuture} will be closed.
     *
     * <p>Usage guidelines for this method:
     *
     * <ul>
     *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
     *       {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
     *       Executor)} instead, with a function that returns the next value directly.
     *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
     *       for every closeable object this step creates in order to capture it for later closing.
     *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
     *       ClosingFuture} call {@link #from(ListenableFuture)}.
     * </ul>
     *
     * <p>The same warnings about doing heavyweight operations within {@link
     * ClosingFuture#transformAsync(AsyncClosingFunction, Executor)} apply here.
     */
    public <U extends @Nullable Object> ClosingFuture<U> callAsync(
        final AsyncClosingFunction4<V1, V2, V3, V4, U> function, Executor executor) {
      return callAsync(
          new AsyncCombiningCallable<U>() {
            @Override
            public ClosingFuture<U> call(DeferredCloser closer, Peeker peeker) throws Exception {
              return function.apply(
                  closer,
                  peeker.getDone(future1),
                  peeker.getDone(future2),
                  peeker.getDone(future3),
                  peeker.getDone(future4));
            }

            @Override
            public String toString() {
              return function.toString();
            }
          },
          executor);
    }
  }

  /**
   * A generic {@link Combiner} that lets you use a lambda or method reference to combine five
   * {@link ClosingFuture}s. Use {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture,
   * ClosingFuture, ClosingFuture)} to start this combination.
   *
   * @param <V1> the type returned by the first future
   * @param <V2> the type returned by the second future
   * @param <V3> the type returned by the third future
   * @param <V4> the type returned by the fourth future
   * @param <V5> the type returned by the fifth future
   */
  public static final class Combiner5<
          V1 extends @Nullable Object,
          V2 extends @Nullable Object,
          V3 extends @Nullable Object,
          V4 extends @Nullable Object,
          V5 extends @Nullable Object>
      extends Combiner {
    /**
     * A function that returns a value when applied to the values of the five futures passed to
     * {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture, ClosingFuture,
     * ClosingFuture)}.
     *
     * @param <V1> the type returned by the first future
     * @param <V2> the type returned by the second future
     * @param <V3> the type returned by the third future
     * @param <V4> the type returned by the fourth future
     * @param <V5> the type returned by the fifth future
     * @param <U> the type returned by the function
     */
    @FunctionalInterface
    public interface ClosingFunction5<
        V1 extends @Nullable Object,
        V2 extends @Nullable Object,
        V3 extends @Nullable Object,
        V4 extends @Nullable Object,
        V5 extends @Nullable Object,
        U extends @Nullable Object> {
      /**
       * Applies this function to five inputs, or throws an exception if unable to do so.
       *
       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
       * (but not before this method completes), even if this method throws or the pipeline is
       * cancelled.
       */
      @ParametricNullness
      U apply(
          DeferredCloser closer,
          @ParametricNullness V1 value1,
          @ParametricNullness V2 value2,
          @ParametricNullness V3 value3,
          @ParametricNullness V4 value4,
          @ParametricNullness V5 value5)
          throws Exception;
    }

    /**
     * A function that returns a {@link ClosingFuture} when applied to the values of the five
     * futures passed to {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture,
     * ClosingFuture, ClosingFuture)}.
     *
     * @param <V1> the type returned by the first future
     * @param <V2> the type returned by the second future
     * @param <V3> the type returned by the third future
     * @param <V4> the type returned by the fourth future
     * @param <V5> the type returned by the fifth future
     * @param <U> the type returned by the function
     */
    @FunctionalInterface
    public interface AsyncClosingFunction5<
        V1 extends @Nullable Object,
        V2 extends @Nullable Object,
        V3 extends @Nullable Object,
        V4 extends @Nullable Object,
        V5 extends @Nullable Object,
        U extends @Nullable Object> {
      /**
       * Applies this function to five inputs, or throws an exception if unable to do so.
       *
       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
       * (but not before this method completes), even if this method throws or the pipeline is
       * cancelled.
       */
      ClosingFuture<U> apply(
          DeferredCloser closer,
          @ParametricNullness V1 value1,
          @ParametricNullness V2 value2,
          @ParametricNullness V3 value3,
          @ParametricNullness V4 value4,
          @ParametricNullness V5 value5)
          throws Exception;
    }

    private final ClosingFuture<V1> future1;
    private final ClosingFuture<V2> future2;
    private final ClosingFuture<V3> future3;
    private final ClosingFuture<V4> future4;
    private final ClosingFuture<V5> future5;

    private Combiner5(
        ClosingFuture<V1> future1,
        ClosingFuture<V2> future2,
        ClosingFuture<V3> future3,
        ClosingFuture<V4> future4,
        ClosingFuture<V5> future5) {
      super(true, ImmutableList.of(future1, future2, future3, future4, future5));
      this.future1 = future1;
      this.future2 = future2;
      this.future3 = future3;
      this.future4 = future4;
      this.future5 = future5;
    }

    /**
     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
     * combining function to their values. The function can use a {@link DeferredCloser} to capture
     * objects to be closed when the pipeline is done.
     *
     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
     * ClosingFuture, ClosingFuture, ClosingFuture)} and any of the inputs fail, so will the
     * returned step.
     *
     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
     *
     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
     * ExecutionException} will be extracted and used as the failure of the derived step.
     */
    public <U extends @Nullable Object> ClosingFuture<U> call(
        final ClosingFunction5<V1, V2, V3, V4, V5, U> function, Executor executor) {
      return call(
          new CombiningCallable<U>() {
            @Override
            @ParametricNullness
            public U call(DeferredCloser closer, Peeker peeker) throws Exception {
              return function.apply(
                  closer,
                  peeker.getDone(future1),
                  peeker.getDone(future2),
                  peeker.getDone(future3),
                  peeker.getDone(future4),
                  peeker.getDone(future5));
            }

            @Override
            public String toString() {
              return function.toString();
            }
          },
          executor);
    }

    /**
     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
     * {@code ClosingFuture}-returning function to their values. The function can use a {@link
     * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
     * captured by the returned {@link ClosingFuture}).
     *
     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
     * ClosingFuture, ClosingFuture, ClosingFuture)} and any of the inputs fail, so will the
     * returned step.
     *
     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
     *
     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
     * ExecutionException} will be extracted and used as the failure of the derived step.
     *
     * <p>If the function throws any other exception, it will be used as the failure of the derived
     * step.
     *
     * <p>If an exception is thrown after the function creates a {@code ClosingFuture}, then none of
     * the closeable objects in that {@code ClosingFuture} will be closed.
     *
     * <p>Usage guidelines for this method:
     *
     * <ul>
     *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
     *       {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
     *       Executor)} instead, with a function that returns the next value directly.
     *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
     *       for every closeable object this step creates in order to capture it for later closing.
     *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
     *       ClosingFuture} call {@link #from(ListenableFuture)}.
     * </ul>
     *
     * <p>The same warnings about doing heavyweight operations within {@link
     * ClosingFuture#transformAsync(AsyncClosingFunction, Executor)} apply here.
     */
    public <U extends @Nullable Object> ClosingFuture<U> callAsync(
        final AsyncClosingFunction5<V1, V2, V3, V4, V5, U> function, Executor executor) {
      return callAsync(
          new AsyncCombiningCallable<U>() {
            @Override
            public ClosingFuture<U> call(DeferredCloser closer, Peeker peeker) throws Exception {
              return function.apply(
                  closer,
                  peeker.getDone(future1),
                  peeker.getDone(future2),
                  peeker.getDone(future3),
                  peeker.getDone(future4),
                  peeker.getDone(future5));
            }

            @Override
            public String toString() {
              return function.toString();
            }
          },
          executor);
    }
  }

  @Override
  public String toString() {
    // TODO(dpb): Better toString, in the style of Futures.transform etc.
    return toStringHelper(this).add("state", state.get()).addValue(future).toString();
  }

  @Override
  protected void finalize() {
    if (state.get().equals(OPEN)) {
      logger.get().log(SEVERE, "Uh oh! An open ClosingFuture has leaked and will close: {0}", this);
      FluentFuture<V> unused = finishToFuture();
    }
  }

  private static void closeQuietly(@CheckForNull final AutoCloseable closeable, Executor executor) {
    if (closeable == null) {
      return;
    }
    try {
      executor.execute(
          () -> {
            try {
              closeable.close();
            } catch (Exception e) {
              /*
               * In guava-jre, any kind of Exception may be thrown because `closeable` has type
               * `AutoCloseable`.
               *
               * In guava-android, the only kinds of Exception that may be thrown are
               * RuntimeException and IOException because `closeable` has type `Closeable`—except
               * that we have to account for sneaky checked exception.
               */
              restoreInterruptIfIsInterruptedException(e);
              logger.get().log(WARNING, "thrown by close()", e);
            }
          });
    } catch (RejectedExecutionException e) {
      if (logger.get().isLoggable(WARNING)) {
        logger
            .get()
            .log(
                WARNING,
                String.format("while submitting close to %s; will close inline", executor),
                e);
      }
      closeQuietly(closeable, directExecutor());
    }
  }

  private void checkAndUpdateState(State oldState, State newState) {
    checkState(
        compareAndUpdateState(oldState, newState),
        "Expected state to be %s, but it was %s",
        oldState,
        newState);
  }

  private boolean compareAndUpdateState(State oldState, State newState) {
    return state.compareAndSet(oldState, newState);
  }

  // TODO(dpb): Should we use a pair of ArrayLists instead of an IdentityHashMap?
  private static final class CloseableList extends IdentityHashMap<AutoCloseable, Executor>
      implements Closeable {
    private final DeferredCloser closer = new DeferredCloser(this);
    private volatile boolean closed;
    @CheckForNull private volatile CountDownLatch whenClosed;

    <V extends @Nullable Object, U extends @Nullable Object>
        ListenableFuture<U> applyClosingFunction(
            ClosingFunction<? super V, U> transformation, @ParametricNullness V input)
            throws Exception {
      // TODO(dpb): Consider ways to defer closing without creating a separate CloseableList.
      CloseableList newCloseables = new CloseableList();
      try {
        return immediateFuture(transformation.apply(newCloseables.closer, input));
      } finally {
        add(newCloseables, directExecutor());
      }
    }

    <V extends @Nullable Object, U extends @Nullable Object>
        FluentFuture<U> applyAsyncClosingFunction(
            AsyncClosingFunction<V, U> transformation, @ParametricNullness V input)
            throws Exception {
      // TODO(dpb): Consider ways to defer closing without creating a separate CloseableList.
      CloseableList newCloseables = new CloseableList();
      try {
        ClosingFuture<U> closingFuture = transformation.apply(newCloseables.closer, input);
        closingFuture.becomeSubsumedInto(newCloseables);
        return closingFuture.future;
      } finally {
        add(newCloseables, directExecutor());
      }
    }

    @Override
    public void close() {
      if (closed) {
        return;
      }
      synchronized (this) {
        if (closed) {
          return;
        }
        closed = true;
      }
      for (Map.Entry<AutoCloseable, Executor> entry : entrySet()) {
        closeQuietly(entry.getKey(), entry.getValue());
      }
      clear();
      if (whenClosed != null) {
        whenClosed.countDown();
      }
    }

    void add(@CheckForNull AutoCloseable closeable, Executor executor) {
      checkNotNull(executor);
      if (closeable == null) {
        return;
      }
      synchronized (this) {
        if (!closed) {
          put(closeable, executor);
          return;
        }
      }
      closeQuietly(closeable, executor);
    }

    /**
     * Returns a latch that reaches zero when this objects' deferred closeables have been closed.
     */
    CountDownLatch whenClosedCountDown() {
      if (closed) {
        return new CountDownLatch(0);
      }
      synchronized (this) {
        if (closed) {
          return new CountDownLatch(0);
        }
        checkState(whenClosed == null);
        return whenClosed = new CountDownLatch(1);
      }
    }
  }

  /**
   * Returns an object that can be used to wait until this objects' deferred closeables have all had
   * {@link Runnable}s that close them submitted to each one's closing {@link Executor}.
   */
  @VisibleForTesting
  CountDownLatch whenClosedCountDown() {
    return closeables.whenClosedCountDown();
  }

  /** The state of a {@link CloseableList}. */
  enum State {
    /** The {@link CloseableList} has not been subsumed or closed. */
    OPEN,

    /**
     * The {@link CloseableList} has been subsumed into another. It may not be closed or subsumed
     * into any other.
     */
    SUBSUMED,

    /**
     * Some {@link ListenableFuture} has a callback attached that will close the {@link
     * CloseableList}, but it has not yet run. The {@link CloseableList} may not be subsumed.
     */
    WILL_CLOSE,

    /**
     * The callback that closes the {@link CloseableList} is running, but it has not completed. The
     * {@link CloseableList} may not be subsumed.
     */
    CLOSING,

    /** The {@link CloseableList} has been closed. It may not be further subsumed. */
    CLOSED,

    /**
     * {@link ClosingFuture#finishToValueAndCloser(ValueAndCloserConsumer, Executor)} has been
     * called. The step may not be further subsumed, nor may {@link #finishToFuture()} be called.
     */
    WILL_CREATE_VALUE_AND_CLOSER,
  }
}