001/*
002 * Copyright (C) 2017 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.util.concurrent;
018
019import static com.google.common.base.Functions.constant;
020import static com.google.common.base.MoreObjects.toStringHelper;
021import static com.google.common.base.Preconditions.checkArgument;
022import static com.google.common.base.Preconditions.checkNotNull;
023import static com.google.common.base.Preconditions.checkState;
024import static com.google.common.collect.Lists.asList;
025import static com.google.common.util.concurrent.ClosingFuture.State.CLOSED;
026import static com.google.common.util.concurrent.ClosingFuture.State.CLOSING;
027import static com.google.common.util.concurrent.ClosingFuture.State.OPEN;
028import static com.google.common.util.concurrent.ClosingFuture.State.SUBSUMED;
029import static com.google.common.util.concurrent.ClosingFuture.State.WILL_CLOSE;
030import static com.google.common.util.concurrent.ClosingFuture.State.WILL_CREATE_VALUE_AND_CLOSER;
031import static com.google.common.util.concurrent.Futures.getDone;
032import static com.google.common.util.concurrent.Futures.immediateFuture;
033import static com.google.common.util.concurrent.Futures.nonCancellationPropagating;
034import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
035import static com.google.common.util.concurrent.Platform.restoreInterruptIfIsInterruptedException;
036import static java.util.logging.Level.FINER;
037import static java.util.logging.Level.SEVERE;
038import static java.util.logging.Level.WARNING;
039
040import com.google.common.annotations.J2ktIncompatible;
041import com.google.common.annotations.VisibleForTesting;
042import com.google.common.collect.FluentIterable;
043import com.google.common.collect.ImmutableList;
044import com.google.common.util.concurrent.ClosingFuture.Combiner.AsyncCombiningCallable;
045import com.google.common.util.concurrent.ClosingFuture.Combiner.CombiningCallable;
046import com.google.common.util.concurrent.Futures.FutureCombiner;
047import com.google.errorprone.annotations.CanIgnoreReturnValue;
048import com.google.errorprone.annotations.DoNotMock;
049import com.google.j2objc.annotations.RetainedWith;
050import java.io.Closeable;
051import java.util.IdentityHashMap;
052import java.util.Map;
053import java.util.concurrent.Callable;
054import java.util.concurrent.CancellationException;
055import java.util.concurrent.CountDownLatch;
056import java.util.concurrent.ExecutionException;
057import java.util.concurrent.Executor;
058import java.util.concurrent.Future;
059import java.util.concurrent.RejectedExecutionException;
060import java.util.concurrent.atomic.AtomicReference;
061import org.checkerframework.checker.nullness.qual.Nullable;
062
063/**
064 * A step in a pipeline of an asynchronous computation. When the last step in the computation is
065 * complete, some objects captured during the computation are closed.
066 *
067 * <p>A pipeline of {@code ClosingFuture}s is a tree of steps. Each step represents either an
068 * asynchronously-computed intermediate value, or else an exception that indicates the failure or
069 * cancellation of the operation so far. The only way to extract the value or exception from a step
070 * is by declaring that step to be the last step of the pipeline. Nevertheless, we refer to the
071 * "value" of a successful step or the "result" (value or exception) of any step.
072 *
073 * <ol>
074 *   <li>A pipeline starts at its leaf step (or steps), which is created from either a callable
075 *       block or a {@link ListenableFuture}.
076 *   <li>Each other step is derived from one or more input steps. At each step, zero or more objects
077 *       can be captured for later closing.
078 *   <li>There is one last step (the root of the tree), from which you can extract the final result
079 *       of the computation. After that result is available (or the computation fails), all objects
080 *       captured by any of the steps in the pipeline are closed.
081 * </ol>
082 *
083 * <h3>Starting a pipeline</h3>
084 *
085 * Start a {@code ClosingFuture} pipeline {@linkplain #submit(ClosingCallable, Executor) from a
086 * callable block} that may capture objects for later closing. To start a pipeline from a {@link
087 * ListenableFuture} that doesn't create resources that should be closed later, you can use {@link
088 * #from(ListenableFuture)} instead.
089 *
090 * <h3>Derived steps</h3>
091 *
092 * A {@code ClosingFuture} step can be derived from one or more input {@code ClosingFuture} steps in
093 * ways similar to {@link FluentFuture}s:
094 *
095 * <ul>
096 *   <li>by transforming the value from a successful input step,
097 *   <li>by catching the exception from a failed input step, or
098 *   <li>by combining the results of several input steps.
099 * </ul>
100 *
101 * Each derivation can capture the next value or any intermediate objects for later closing.
102 *
103 * <p>A step can be the input to at most one derived step. Once you transform its value, catch its
104 * exception, or combine it with others, you cannot do anything else with it, including declare it
105 * to be the last step of the pipeline.
106 *
107 * <h4>Transforming</h4>
108 *
109 * To derive the next step by asynchronously applying a function to an input step's value, call
110 * {@link #transform(ClosingFunction, Executor)} or {@link #transformAsync(AsyncClosingFunction,
111 * Executor)} on the input step.
112 *
113 * <h4>Catching</h4>
114 *
115 * To derive the next step from a failed input step, call {@link #catching(Class, ClosingFunction,
116 * Executor)} or {@link #catchingAsync(Class, AsyncClosingFunction, Executor)} on the input step.
117 *
118 * <h4>Combining</h4>
119 *
120 * To derive a {@code ClosingFuture} from two or more input steps, pass the input steps to {@link
121 * #whenAllComplete(Iterable)} or {@link #whenAllSucceed(Iterable)} or its overloads.
122 *
123 * <h3>Cancelling</h3>
124 *
125 * Any step in a pipeline can be {@linkplain #cancel(boolean) cancelled}, even after another step
126 * has been derived, with the same semantics as cancelling a {@link Future}. In addition, a
127 * successfully cancelled step will immediately start closing all objects captured for later closing
128 * by it and by its input steps.
129 *
130 * <h3>Ending a pipeline</h3>
131 *
132 * Each {@code ClosingFuture} pipeline must be ended. To end a pipeline, decide whether you want to
133 * close the captured objects automatically or manually.
134 *
135 * <h4>Automatically closing</h4>
136 *
137 * You can extract a {@link Future} that represents the result of the last step in the pipeline by
138 * calling {@link #finishToFuture()}. All objects the pipeline has captured for closing will begin
139 * to be closed asynchronously <b>after</b> the returned {@code Future} is done: the future
140 * completes before closing starts, rather than once it has finished.
141 *
142 * <pre>{@code
143 * FluentFuture<UserName> userName =
144 *     ClosingFuture.submit(
145 *             closer -> closer.eventuallyClose(database.newTransaction(), closingExecutor),
146 *             executor)
147 *         .transformAsync((closer, transaction) -> transaction.queryClosingFuture("..."), executor)
148 *         .transform((closer, result) -> result.get("userName"), directExecutor())
149 *         .catching(DBException.class, e -> "no user", directExecutor())
150 *         .finishToFuture();
151 * }</pre>
152 *
153 * In this example, when the {@code userName} {@link Future} is done, the transaction and the query
154 * result cursor will both be closed, even if the operation is cancelled or fails.
155 *
156 * <h4>Manually closing</h4>
157 *
158 * If you want to close the captured objects manually, after you've used the final result, call
159 * {@link #finishToValueAndCloser(ValueAndCloserConsumer, Executor)} to get an object that holds the
160 * final result. You then call {@link ValueAndCloser#closeAsync()} to close the captured objects.
161 *
162 * <pre>{@code
163 *     ClosingFuture.submit(
164 *             closer -> closer.eventuallyClose(database.newTransaction(), closingExecutor),
165 *             executor)
166 *     .transformAsync((closer, transaction) -> transaction.queryClosingFuture("..."), executor)
167 *     .transform((closer, result) -> result.get("userName"), directExecutor())
168 *     .catching(DBException.class, e -> "no user", directExecutor())
169 *     .finishToValueAndCloser(
170 *         valueAndCloser -> this.userNameValueAndCloser = valueAndCloser, executor);
171 *
172 * // later
173 * try { // get() will throw if the operation failed or was cancelled.
174 *   UserName userName = userNameValueAndCloser.get();
175 *   // do something with userName
176 * } finally {
177 *   userNameValueAndCloser.closeAsync();
178 * }
179 * }</pre>
180 *
181 * In this example, when {@code userNameValueAndCloser.closeAsync()} is called, the transaction and
182 * the query result cursor will both be closed, even if the operation is cancelled or fails.
183 *
184 * <p>Note that if you don't call {@code closeAsync()}, the captured objects will not be closed. The
185 * automatic-closing approach described above is safer.
186 *
187 * @param <V> the type of the value of this step
188 * @since 30.0
189 */
190// TODO(dpb): Consider reusing one CloseableList for the entire pipeline, modulo combinations.
191@DoNotMock("Use ClosingFuture.from(Futures.immediate*Future)")
192@J2ktIncompatible
193// TODO(dpb): GWT compatibility.
194public final class ClosingFuture<V extends @Nullable Object> {
195
196  private static final LazyLogger logger = new LazyLogger(ClosingFuture.class);
197
198  /**
199   * An object that can capture objects to be closed later, when a {@link ClosingFuture} pipeline is
200   * done.
201   */
202  public static final class DeferredCloser {
203    @RetainedWith private final CloseableList list;
204
205    DeferredCloser(CloseableList list) {
206      this.list = list;
207    }
208
209    /**
210     * Captures an object to be closed when a {@link ClosingFuture} pipeline is done.
211     *
212     * <p>For users of the {@code -jre} flavor of Guava, the object can be any {@code
213     * AutoCloseable}. For users of the {@code -android} flavor, the object must be a {@code
214     * Closeable}. (For more about the flavors, see <a
215     * href="https://github.com/google/guava#adding-guava-to-your-build">Adding Guava to your
216     * build</a>.)
217     *
218     * <p>Be careful when targeting an older SDK than you are building against (most commonly when
219     * building for Android): Ensure that any object you pass implements the interface not just in
220     * your current SDK version but also at the oldest version you support. For example, <a
221     * href="https://developer.android.com/sdk/api_diff/16/">API Level 16</a> is the first version
222     * in which {@code Cursor} is {@code Closeable}. To support older versions, pass a wrapper
223     * {@code Closeable} with a method reference like {@code cursor::close}.
224     *
225     * <p>Note that this method is still binary-compatible between flavors because the erasure of
226     * its parameter type is {@code Object}, not {@code AutoCloseable} or {@code Closeable}.
227     *
228     * @param closeable the object to be closed (see notes above)
229     * @param closingExecutor the object will be closed on this executor
230     * @return the first argument
231     */
232    @CanIgnoreReturnValue
233    @ParametricNullness
234    public <C extends @Nullable Object & @Nullable AutoCloseable> C eventuallyClose(
235        @ParametricNullness C closeable, Executor closingExecutor) {
236      checkNotNull(closingExecutor);
237      if (closeable != null) {
238        list.add(closeable, closingExecutor);
239      }
240      return closeable;
241    }
242  }
243
244  /**
245   * An operation that computes a result.
246   *
247   * @param <V> the type of the result
248   */
249  public interface ClosingCallable<V extends @Nullable Object> {
250    /**
251     * Computes a result, or throws an exception if unable to do so.
252     *
253     * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
254     * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
255     * not before this method completes), even if this method throws or the pipeline is cancelled.
256     */
257    @ParametricNullness
258    V call(DeferredCloser closer) throws Exception;
259  }
260
261  /**
262   * An operation that computes a {@link ClosingFuture} of a result.
263   *
264   * @param <V> the type of the result
265   * @since 30.1
266   */
267  public interface AsyncClosingCallable<V extends @Nullable Object> {
268    /**
269     * Computes a result, or throws an exception if unable to do so.
270     *
271     * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
272     * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
273     * not before this method completes), even if this method throws or the pipeline is cancelled.
274     */
275    ClosingFuture<V> call(DeferredCloser closer) throws Exception;
276  }
277
278  /**
279   * A function from an input to a result.
280   *
281   * @param <T> the type of the input to the function
282   * @param <U> the type of the result of the function
283   */
284  public interface ClosingFunction<T extends @Nullable Object, U extends @Nullable Object> {
285
286    /**
287     * Applies this function to an input, or throws an exception if unable to do so.
288     *
289     * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
290     * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
291     * not before this method completes), even if this method throws or the pipeline is cancelled.
292     */
293    @ParametricNullness
294    U apply(DeferredCloser closer, @ParametricNullness T input) throws Exception;
295  }
296
297  /**
298   * A function from an input to a {@link ClosingFuture} of a result.
299   *
300   * @param <T> the type of the input to the function
301   * @param <U> the type of the result of the function
302   */
303  public interface AsyncClosingFunction<T extends @Nullable Object, U extends @Nullable Object> {
304    /**
305     * Applies this function to an input, or throws an exception if unable to do so.
306     *
307     * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
308     * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done (but
309     * not before this method completes), even if this method throws or the pipeline is cancelled.
310     */
311    ClosingFuture<U> apply(DeferredCloser closer, @ParametricNullness T input) throws Exception;
312  }
313
314  /**
315   * An object that holds the final result of an asynchronous {@link ClosingFuture} operation and
316   * allows the user to close all the closeable objects that were captured during it for later
317   * closing.
318   *
319   * <p>The asynchronous operation will have completed before this object is created.
320   *
321   * @param <V> the type of the value of a successful operation
322   * @see ClosingFuture#finishToValueAndCloser(ValueAndCloserConsumer, Executor)
323   */
324  public static final class ValueAndCloser<V extends @Nullable Object> {
325
326    private final ClosingFuture<? extends V> closingFuture;
327
328    ValueAndCloser(ClosingFuture<? extends V> closingFuture) {
329      this.closingFuture = checkNotNull(closingFuture);
330    }
331
332    /**
333     * Returns the final value of the associated {@link ClosingFuture}, or throws an exception as
334     * {@link Future#get()} would.
335     *
336     * <p>Because the asynchronous operation has already completed, this method is synchronous and
337     * returns immediately.
338     *
339     * @throws CancellationException if the computation was cancelled
340     * @throws ExecutionException if the computation threw an exception
341     */
342    @ParametricNullness
343    public V get() throws ExecutionException {
344      return getDone(closingFuture.future);
345    }
346
347    /**
348     * Starts closing all closeable objects captured during the {@link ClosingFuture}'s asynchronous
349     * operation on the {@link Executor}s specified by calls to {@link
350     * DeferredCloser#eventuallyClose(Object, Executor)}.
351     *
352     * <p>If any such calls specified {@link MoreExecutors#directExecutor()}, those objects will be
353     * closed synchronously.
354     *
355     * <p>Idempotent: objects will be closed at most once.
356     */
357    public void closeAsync() {
358      closingFuture.close();
359    }
360  }
361
362  /**
363   * Represents an operation that accepts a {@link ValueAndCloser} for the last step in a {@link
364   * ClosingFuture} pipeline.
365   *
366   * @param <V> the type of the final value of a successful pipeline
367   * @see ClosingFuture#finishToValueAndCloser(ValueAndCloserConsumer, Executor)
368   */
369  public interface ValueAndCloserConsumer<V extends @Nullable Object> {
370
371    /** Accepts a {@link ValueAndCloser} for the last step in a {@link ClosingFuture} pipeline. */
372    void accept(ValueAndCloser<V> valueAndCloser);
373  }
374
375  /**
376   * Starts a {@link ClosingFuture} pipeline by submitting a callable block to an executor.
377   *
378   * @throws java.util.concurrent.RejectedExecutionException if the task cannot be scheduled for
379   *     execution
380   */
381  public static <V extends @Nullable Object> ClosingFuture<V> submit(
382      ClosingCallable<V> callable, Executor executor) {
383    checkNotNull(callable);
384    CloseableList closeables = new CloseableList();
385    TrustedListenableFutureTask<V> task =
386        TrustedListenableFutureTask.create(
387            new Callable<V>() {
388              @Override
389              @ParametricNullness
390              public V call() throws Exception {
391                return callable.call(closeables.closer);
392              }
393
394              @Override
395              public String toString() {
396                return callable.toString();
397              }
398            });
399    executor.execute(task);
400    return new ClosingFuture<>(task, closeables);
401  }
402
403  /**
404   * Starts a {@link ClosingFuture} pipeline by submitting a callable block to an executor.
405   *
406   * @throws java.util.concurrent.RejectedExecutionException if the task cannot be scheduled for
407   *     execution
408   * @since 30.1
409   */
410  public static <V extends @Nullable Object> ClosingFuture<V> submitAsync(
411      AsyncClosingCallable<V> callable, Executor executor) {
412    checkNotNull(callable);
413    CloseableList closeables = new CloseableList();
414    TrustedListenableFutureTask<V> task =
415        TrustedListenableFutureTask.create(
416            new AsyncCallable<V>() {
417              @Override
418              public ListenableFuture<V> call() throws Exception {
419                CloseableList newCloseables = new CloseableList();
420                try {
421                  ClosingFuture<V> closingFuture = callable.call(newCloseables.closer);
422                  closingFuture.becomeSubsumedInto(closeables);
423                  return closingFuture.future;
424                } finally {
425                  closeables.add(newCloseables, directExecutor());
426                }
427              }
428
429              @Override
430              public String toString() {
431                return callable.toString();
432              }
433            });
434    executor.execute(task);
435    return new ClosingFuture<>(task, closeables);
436  }
437
438  /**
439   * Starts a {@link ClosingFuture} pipeline with a {@link ListenableFuture}.
440   *
441   * <p>{@code future}'s value will not be closed when the pipeline is done even if {@code V}
442   * implements {@link Closeable}. In order to start a pipeline with a value that will be closed
443   * when the pipeline is done, use {@link #submit(ClosingCallable, Executor)} instead.
444   */
445  public static <V extends @Nullable Object> ClosingFuture<V> from(ListenableFuture<V> future) {
446    return new ClosingFuture<>(future);
447  }
448
449  /**
450   * Starts a {@link ClosingFuture} pipeline with a {@link ListenableFuture}.
451   *
452   * <p>If {@code future} succeeds, its value will be closed (using {@code closingExecutor)}) when
453   * the pipeline is done, even if the pipeline is canceled or fails.
454   *
455   * <p>Cancelling the pipeline will not cancel {@code future}, so that the pipeline can access its
456   * value in order to close it.
457   *
458   * @param future the future to create the {@code ClosingFuture} from. For discussion of the
459   *     future's result type {@code C}, see {@link DeferredCloser#eventuallyClose(Object,
460   *     Executor)}.
461   * @param closingExecutor the future's result will be closed on this executor
462   * @deprecated Creating {@link Future}s of closeable types is dangerous in general because the
463   *     underlying value may never be closed if the {@link Future} is canceled after its operation
464   *     begins. Consider replacing code that creates {@link ListenableFuture}s of closeable types,
465   *     including those that pass them to this method, with {@link #submit(ClosingCallable,
466   *     Executor)} in order to ensure that resources do not leak. Or, to start a pipeline with a
467   *     {@link ListenableFuture} that doesn't create values that should be closed, use {@link
468   *     ClosingFuture#from}.
469   */
470  @Deprecated
471  public static <C extends @Nullable Object & @Nullable AutoCloseable>
472      ClosingFuture<C> eventuallyClosing(
473          ListenableFuture<C> future, final Executor closingExecutor) {
474    checkNotNull(closingExecutor);
475    final ClosingFuture<C> closingFuture = new ClosingFuture<>(nonCancellationPropagating(future));
476    Futures.addCallback(
477        future,
478        new FutureCallback<@Nullable AutoCloseable>() {
479          @Override
480          public void onSuccess(@Nullable AutoCloseable result) {
481            closingFuture.closeables.closer.eventuallyClose(result, closingExecutor);
482          }
483
484          @Override
485          public void onFailure(Throwable t) {}
486        },
487        directExecutor());
488    return closingFuture;
489  }
490
491  /**
492   * Starts specifying how to combine {@link ClosingFuture}s into a single pipeline.
493   *
494   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
495   *     the {@code futures}, or if any has already been {@linkplain #finishToFuture() finished}
496   */
497  public static Combiner whenAllComplete(Iterable<? extends ClosingFuture<?>> futures) {
498    return new Combiner(false, futures);
499  }
500
501  /**
502   * Starts specifying how to combine {@link ClosingFuture}s into a single pipeline.
503   *
504   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
505   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
506   */
507  public static Combiner whenAllComplete(
508      ClosingFuture<?> future1, ClosingFuture<?>... moreFutures) {
509    return whenAllComplete(asList(future1, moreFutures));
510  }
511
512  /**
513   * Starts specifying how to combine {@link ClosingFuture}s into a single pipeline, assuming they
514   * all succeed. If any fail, the resulting pipeline will fail.
515   *
516   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
517   *     the {@code futures}, or if any has already been {@linkplain #finishToFuture() finished}
518   */
519  public static Combiner whenAllSucceed(Iterable<? extends ClosingFuture<?>> futures) {
520    return new Combiner(true, futures);
521  }
522
523  /**
524   * Starts specifying how to combine two {@link ClosingFuture}s into a single pipeline, assuming
525   * they all succeed. If any fail, the resulting pipeline will fail.
526   *
527   * <p>Calling this method allows you to use lambdas or method references typed with the types of
528   * the input {@link ClosingFuture}s.
529   *
530   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
531   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
532   */
533  public static <V1 extends @Nullable Object, V2 extends @Nullable Object>
534      Combiner2<V1, V2> whenAllSucceed(ClosingFuture<V1> future1, ClosingFuture<V2> future2) {
535    return new Combiner2<>(future1, future2);
536  }
537
538  /**
539   * Starts specifying how to combine three {@link ClosingFuture}s into a single pipeline, assuming
540   * they all succeed. If any fail, the resulting pipeline will fail.
541   *
542   * <p>Calling this method allows you to use lambdas or method references typed with the types of
543   * the input {@link ClosingFuture}s.
544   *
545   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
546   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
547   */
548  public static <
549          V1 extends @Nullable Object, V2 extends @Nullable Object, V3 extends @Nullable Object>
550      Combiner3<V1, V2, V3> whenAllSucceed(
551          ClosingFuture<V1> future1, ClosingFuture<V2> future2, ClosingFuture<V3> future3) {
552    return new Combiner3<>(future1, future2, future3);
553  }
554
555  /**
556   * Starts specifying how to combine four {@link ClosingFuture}s into a single pipeline, assuming
557   * they all succeed. If any fail, the resulting pipeline will fail.
558   *
559   * <p>Calling this method allows you to use lambdas or method references typed with the types of
560   * the input {@link ClosingFuture}s.
561   *
562   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
563   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
564   */
565  public static <
566          V1 extends @Nullable Object,
567          V2 extends @Nullable Object,
568          V3 extends @Nullable Object,
569          V4 extends @Nullable Object>
570      Combiner4<V1, V2, V3, V4> whenAllSucceed(
571          ClosingFuture<V1> future1,
572          ClosingFuture<V2> future2,
573          ClosingFuture<V3> future3,
574          ClosingFuture<V4> future4) {
575    return new Combiner4<>(future1, future2, future3, future4);
576  }
577
578  /**
579   * Starts specifying how to combine five {@link ClosingFuture}s into a single pipeline, assuming
580   * they all succeed. If any fail, the resulting pipeline will fail.
581   *
582   * <p>Calling this method allows you to use lambdas or method references typed with the types of
583   * the input {@link ClosingFuture}s.
584   *
585   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
586   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
587   */
588  public static <
589          V1 extends @Nullable Object,
590          V2 extends @Nullable Object,
591          V3 extends @Nullable Object,
592          V4 extends @Nullable Object,
593          V5 extends @Nullable Object>
594      Combiner5<V1, V2, V3, V4, V5> whenAllSucceed(
595          ClosingFuture<V1> future1,
596          ClosingFuture<V2> future2,
597          ClosingFuture<V3> future3,
598          ClosingFuture<V4> future4,
599          ClosingFuture<V5> future5) {
600    return new Combiner5<>(future1, future2, future3, future4, future5);
601  }
602
603  /**
604   * Starts specifying how to combine {@link ClosingFuture}s into a single pipeline, assuming they
605   * all succeed. If any fail, the resulting pipeline will fail.
606   *
607   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from any of
608   *     the arguments, or if any has already been {@linkplain #finishToFuture() finished}
609   */
610  public static Combiner whenAllSucceed(
611      ClosingFuture<?> future1,
612      ClosingFuture<?> future2,
613      ClosingFuture<?> future3,
614      ClosingFuture<?> future4,
615      ClosingFuture<?> future5,
616      ClosingFuture<?> future6,
617      ClosingFuture<?>... moreFutures) {
618    return whenAllSucceed(
619        FluentIterable.of(future1, future2, future3, future4, future5, future6)
620            .append(moreFutures));
621  }
622
623  private final AtomicReference<State> state = new AtomicReference<>(OPEN);
624  private final CloseableList closeables;
625  private final FluentFuture<V> future;
626
627  private ClosingFuture(ListenableFuture<V> future) {
628    this(future, new CloseableList());
629  }
630
631  private ClosingFuture(ListenableFuture<V> future, CloseableList closeables) {
632    this.future = FluentFuture.from(future);
633    this.closeables = closeables;
634  }
635
636  /**
637   * Returns a future that finishes when this step does. Calling {@code get()} on the returned
638   * future returns {@code null} if the step is successful or throws the same exception that would
639   * be thrown by calling {@code finishToFuture().get()} if this were the last step. Calling {@code
640   * cancel()} on the returned future has no effect on the {@code ClosingFuture} pipeline.
641   *
642   * <p>{@code statusFuture} differs from most methods on {@code ClosingFuture}: You can make calls
643   * to {@code statusFuture} <i>in addition to</i> the call you make to {@link #finishToFuture()} or
644   * a derivation method <i>on the same instance</i>. This is important because calling {@code
645   * statusFuture} alone does not provide a way to close the pipeline.
646   */
647  public ListenableFuture<?> statusFuture() {
648    return nonCancellationPropagating(future.transform(constant(null), directExecutor()));
649  }
650
651  /**
652   * Returns a new {@code ClosingFuture} pipeline step derived from this one by applying a function
653   * to its value. The function can use a {@link DeferredCloser} to capture objects to be closed
654   * when the pipeline is done.
655   *
656   * <p>If this {@code ClosingFuture} fails, the function will not be called, and the derived {@code
657   * ClosingFuture} will be equivalent to this one.
658   *
659   * <p>If the function throws an exception, that exception is used as the result of the derived
660   * {@code ClosingFuture}.
661   *
662   * <p>Example usage:
663   *
664   * <pre>{@code
665   * ClosingFuture<List<Row>> rowsFuture =
666   *     queryFuture.transform((closer, result) -> result.getRows(), executor);
667   * }</pre>
668   *
669   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
670   * the discussion in the {@link ListenableFuture#addListener} documentation. All its warnings
671   * about heavyweight listeners are also applicable to heavyweight functions passed to this method.
672   *
673   * <p>After calling this method, you may not call {@link #finishToFuture()}, {@link
674   * #finishToValueAndCloser(ValueAndCloserConsumer, Executor)}, or any other derivation method on
675   * the original {@code ClosingFuture} instance.
676   *
677   * @param function transforms the value of this step to the value of the derived step
678   * @param executor executor to run the function in
679   * @return the derived step
680   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from this
681   *     one, or if this {@code ClosingFuture} has already been {@linkplain #finishToFuture()
682   *     finished}
683   */
684  public <U extends @Nullable Object> ClosingFuture<U> transform(
685      final ClosingFunction<? super V, U> function, Executor executor) {
686    checkNotNull(function);
687    AsyncFunction<V, U> applyFunction =
688        new AsyncFunction<V, U>() {
689          @Override
690          public ListenableFuture<U> apply(V input) throws Exception {
691            return closeables.applyClosingFunction(function, input);
692          }
693
694          @Override
695          public String toString() {
696            return function.toString();
697          }
698        };
699    // TODO(dpb): Switch to future.transformSync when that exists (passing a throwing function).
700    return derive(future.transformAsync(applyFunction, executor));
701  }
702
703  /**
704   * Returns a new {@code ClosingFuture} pipeline step derived from this one by applying a function
705   * that returns a {@code ClosingFuture} to its value. The function can use a {@link
706   * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
707   * captured by the returned {@link ClosingFuture}).
708   *
709   * <p>If this {@code ClosingFuture} succeeds, the derived one will be equivalent to the one
710   * returned by the function.
711   *
712   * <p>If this {@code ClosingFuture} fails, the function will not be called, and the derived {@code
713   * ClosingFuture} will be equivalent to this one.
714   *
715   * <p>If the function throws an exception, that exception is used as the result of the derived
716   * {@code ClosingFuture}. But if the exception is thrown after the function creates a {@code
717   * ClosingFuture}, then none of the closeable objects in that {@code ClosingFuture} will be
718   * closed.
719   *
720   * <p>Usage guidelines for this method:
721   *
722   * <ul>
723   *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
724   *       {@code ClosingFuture}. If possible, prefer calling {@link #transform(ClosingFunction,
725   *       Executor)} instead, with a function that returns the next value directly.
726   *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
727   *       for every closeable object this step creates in order to capture it for later closing.
728   *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
729   *       ClosingFuture} call {@link #from(ListenableFuture)}.
730   *   <li>In case this step doesn't create new closeables, you can adapt an API that returns a
731   *       {@link ListenableFuture} to return a {@code ClosingFuture} by wrapping it with a call to
732   *       {@link #withoutCloser(AsyncFunction)}
733   * </ul>
734   *
735   * <p>Example usage:
736   *
737   * <pre>{@code
738   * // Result.getRowsClosingFuture() returns a ClosingFuture.
739   * ClosingFuture<List<Row>> rowsFuture =
740   *     queryFuture.transformAsync((closer, result) -> result.getRowsClosingFuture(), executor);
741   *
742   * // Result.writeRowsToOutputStreamFuture() returns a ListenableFuture that resolves to the
743   * // number of written rows. openOutputFile() returns a FileOutputStream (which implements
744   * // Closeable).
745   * ClosingFuture<Integer> rowsFuture2 =
746   *     queryFuture.transformAsync(
747   *         (closer, result) -> {
748   *           FileOutputStream fos = closer.eventuallyClose(openOutputFile(), closingExecutor);
749   *           return ClosingFuture.from(result.writeRowsToOutputStreamFuture(fos));
750   *      },
751   *      executor);
752   *
753   * // Result.getRowsFuture() returns a ListenableFuture (no new closeables are created).
754   * ClosingFuture<List<Row>> rowsFuture3 =
755   *     queryFuture.transformAsync(withoutCloser(Result::getRowsFuture), executor);
756   *
757   * }</pre>
758   *
759   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
760   * the discussion in the {@link ListenableFuture#addListener} documentation. All its warnings
761   * about heavyweight listeners are also applicable to heavyweight functions passed to this method.
762   * (Specifically, {@code directExecutor} functions should avoid heavyweight operations inside
763   * {@code AsyncClosingFunction.apply}. Any heavyweight operations should occur in other threads
764   * responsible for completing the returned {@code ClosingFuture}.)
765   *
766   * <p>After calling this method, you may not call {@link #finishToFuture()}, {@link
767   * #finishToValueAndCloser(ValueAndCloserConsumer, Executor)}, or any other derivation method on
768   * the original {@code ClosingFuture} instance.
769   *
770   * @param function transforms the value of this step to a {@code ClosingFuture} with the value of
771   *     the derived step
772   * @param executor executor to run the function in
773   * @return the derived step
774   * @throws IllegalStateException if a {@code ClosingFuture} has already been derived from this
775   *     one, or if this {@code ClosingFuture} has already been {@linkplain #finishToFuture()
776   *     finished}
777   */
778  public <U extends @Nullable Object> ClosingFuture<U> transformAsync(
779      final AsyncClosingFunction<? super V, U> function, Executor executor) {
780    checkNotNull(function);
781    AsyncFunction<V, U> applyFunction =
782        new AsyncFunction<V, U>() {
783          @Override
784          public ListenableFuture<U> apply(V input) throws Exception {
785            return closeables.applyAsyncClosingFunction(function, input);
786          }
787
788          @Override
789          public String toString() {
790            return function.toString();
791          }
792        };
793    return derive(future.transformAsync(applyFunction, executor));
794  }
795
796  /**
797   * Returns an {@link AsyncClosingFunction} that applies an {@link AsyncFunction} to an input,
798   * ignoring the DeferredCloser and returning a {@code ClosingFuture} derived from the returned
799   * {@link ListenableFuture}.
800   *
801   * <p>Use this method to pass a transformation to {@link #transformAsync(AsyncClosingFunction,
802   * Executor)} or to {@link #catchingAsync(Class, AsyncClosingFunction, Executor)} as long as it
803   * meets these conditions:
804   *
805   * <ul>
806   *   <li>It does not need to capture any {@link Closeable} objects by calling {@link
807   *       DeferredCloser#eventuallyClose(Object, Executor)}.
808   *   <li>It returns a {@link ListenableFuture}.
809   * </ul>
810   *
811   * <p>Example usage:
812   *
813   * <pre>{@code
814   * // Result.getRowsFuture() returns a ListenableFuture.
815   * ClosingFuture<List<Row>> rowsFuture =
816   *     queryFuture.transformAsync(withoutCloser(Result::getRowsFuture), executor);
817   * }</pre>
818   *
819   * @param function transforms the value of a {@code ClosingFuture} step to a {@link
820   *     ListenableFuture} with the value of a derived step
821   */
822  public static <V extends @Nullable Object, U extends @Nullable Object>
823      AsyncClosingFunction<V, U> withoutCloser(final AsyncFunction<V, U> function) {
824    checkNotNull(function);
825    return new AsyncClosingFunction<V, U>() {
826      @Override
827      public ClosingFuture<U> apply(DeferredCloser closer, V input) throws Exception {
828        return ClosingFuture.from(function.apply(input));
829      }
830    };
831  }
832
833  /**
834   * Returns a new {@code ClosingFuture} pipeline step derived from this one by applying a function
835   * to its exception if it is an instance of a given exception type. The function can use a {@link
836   * DeferredCloser} to capture objects to be closed when the pipeline is done.
837   *
838   * <p>If this {@code ClosingFuture} succeeds or fails with a different exception type, the
839   * function will not be called, and the derived {@code ClosingFuture} will be equivalent to this
840   * one.
841   *
842   * <p>If the function throws an exception, that exception is used as the result of the derived
843   * {@code ClosingFuture}.
844   *
845   * <p>Example usage:
846   *
847   * <pre>{@code
848   * ClosingFuture<QueryResult> queryFuture =
849   *     queryFuture.catching(
850   *         QueryException.class, (closer, x) -> Query.emptyQueryResult(), executor);
851   * }</pre>
852   *
853   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
854   * the discussion in the {@link ListenableFuture#addListener} documentation. All its warnings
855   * about heavyweight listeners are also applicable to heavyweight functions passed to this method.
856   *
857   * <p>After calling this method, you may not call {@link #finishToFuture()}, {@link
858   * #finishToValueAndCloser(ValueAndCloserConsumer, Executor)}, or any other derivation method on
859   * the original {@code ClosingFuture} instance.
860   *
861   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
862   *     type is matched against this step's exception. "This step's exception" means the cause of
863   *     the {@link ExecutionException} thrown by {@link Future#get()} on the {@link Future}
864   *     underlying this step or, if {@code get()} throws a different kind of exception, that
865   *     exception itself. To avoid hiding bugs and other unrecoverable errors, callers should
866   *     prefer more specific types, avoiding {@code Throwable.class} in particular.
867   * @param fallback the function to be called if this step fails with the expected exception type.
868   *     The function's argument is this step's exception. "This step's exception" means the cause
869   *     of the {@link ExecutionException} thrown by {@link Future#get()} on the {@link Future}
870   *     underlying this step or, if {@code get()} throws a different kind of exception, that
871   *     exception itself.
872   * @param executor the executor that runs {@code fallback} if the input fails
873   */
874  public <X extends Throwable> ClosingFuture<V> catching(
875      Class<X> exceptionType, ClosingFunction<? super X, ? extends V> fallback, Executor executor) {
876    return catchingMoreGeneric(exceptionType, fallback, executor);
877  }
878
879  // Avoids generic type capture inconsistency problems where |? extends V| is incompatible with V.
880  private <X extends Throwable, W extends V> ClosingFuture<V> catchingMoreGeneric(
881      Class<X> exceptionType, final ClosingFunction<? super X, W> fallback, Executor executor) {
882    checkNotNull(fallback);
883    AsyncFunction<X, W> applyFallback =
884        new AsyncFunction<X, W>() {
885          @Override
886          public ListenableFuture<W> apply(X exception) throws Exception {
887            return closeables.applyClosingFunction(fallback, exception);
888          }
889
890          @Override
891          public String toString() {
892            return fallback.toString();
893          }
894        };
895    // TODO(dpb): Switch to future.catchingSync when that exists (passing a throwing function).
896    return derive(future.catchingAsync(exceptionType, applyFallback, executor));
897  }
898
899  /**
900   * Returns a new {@code ClosingFuture} pipeline step derived from this one by applying a function
901   * that returns a {@code ClosingFuture} to its exception if it is an instance of a given exception
902   * type. The function can use a {@link DeferredCloser} to capture objects to be closed when the
903   * pipeline is done (other than those captured by the returned {@link ClosingFuture}).
904   *
905   * <p>If this {@code ClosingFuture} fails with an exception of the given type, the derived {@code
906   * ClosingFuture} will be equivalent to the one returned by the function.
907   *
908   * <p>If this {@code ClosingFuture} succeeds or fails with a different exception type, the
909   * function will not be called, and the derived {@code ClosingFuture} will be equivalent to this
910   * one.
911   *
912   * <p>If the function throws an exception, that exception is used as the result of the derived
913   * {@code ClosingFuture}. But if the exception is thrown after the function creates a {@code
914   * ClosingFuture}, then none of the closeable objects in that {@code ClosingFuture} will be
915   * closed.
916   *
917   * <p>Usage guidelines for this method:
918   *
919   * <ul>
920   *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
921   *       {@code ClosingFuture}. If possible, prefer calling {@link #catching(Class,
922   *       ClosingFunction, Executor)} instead, with a function that returns the next value
923   *       directly.
924   *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
925   *       for every closeable object this step creates in order to capture it for later closing.
926   *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
927   *       ClosingFuture} call {@link #from(ListenableFuture)}.
928   *   <li>In case this step doesn't create new closeables, you can adapt an API that returns a
929   *       {@link ListenableFuture} to return a {@code ClosingFuture} by wrapping it with a call to
930   *       {@link #withoutCloser(AsyncFunction)}
931   * </ul>
932   *
933   * <p>Example usage:
934   *
935   * <pre>{@code
936   * // Fall back to a secondary input stream in case of IOException.
937   * ClosingFuture<InputStream> inputFuture =
938   *     firstInputFuture.catchingAsync(
939   *         IOException.class, (closer, x) -> secondaryInputStreamClosingFuture(), executor);
940   * }
941   * }</pre>
942   *
943   * <p>When selecting an executor, note that {@code directExecutor} is dangerous in some cases. See
944   * the discussion in the {@link ListenableFuture#addListener} documentation. All its warnings
945   * about heavyweight listeners are also applicable to heavyweight functions passed to this method.
946   * (Specifically, {@code directExecutor} functions should avoid heavyweight operations inside
947   * {@code AsyncClosingFunction.apply}. Any heavyweight operations should occur in other threads
948   * responsible for completing the returned {@code ClosingFuture}.)
949   *
950   * <p>After calling this method, you may not call {@link #finishToFuture()}, {@link
951   * #finishToValueAndCloser(ValueAndCloserConsumer, Executor)}, or any other derivation method on
952   * the original {@code ClosingFuture} instance.
953   *
954   * @param exceptionType the exception type that triggers use of {@code fallback}. The exception
955   *     type is matched against this step's exception. "This step's exception" means the cause of
956   *     the {@link ExecutionException} thrown by {@link Future#get()} on the {@link Future}
957   *     underlying this step or, if {@code get()} throws a different kind of exception, that
958   *     exception itself. To avoid hiding bugs and other unrecoverable errors, callers should
959   *     prefer more specific types, avoiding {@code Throwable.class} in particular.
960   * @param fallback the function to be called if this step fails with the expected exception type.
961   *     The function's argument is this step's exception. "This step's exception" means the cause
962   *     of the {@link ExecutionException} thrown by {@link Future#get()} on the {@link Future}
963   *     underlying this step or, if {@code get()} throws a different kind of exception, that
964   *     exception itself.
965   * @param executor the executor that runs {@code fallback} if the input fails
966   */
967  // TODO(dpb): Should this do something special if the function throws CancellationException or
968  // ExecutionException?
969  public <X extends Throwable> ClosingFuture<V> catchingAsync(
970      Class<X> exceptionType,
971      AsyncClosingFunction<? super X, ? extends V> fallback,
972      Executor executor) {
973    return catchingAsyncMoreGeneric(exceptionType, fallback, executor);
974  }
975
976  // Avoids generic type capture inconsistency problems where |? extends V| is incompatible with V.
977  private <X extends Throwable, W extends V> ClosingFuture<V> catchingAsyncMoreGeneric(
978      Class<X> exceptionType,
979      final AsyncClosingFunction<? super X, W> fallback,
980      Executor executor) {
981    checkNotNull(fallback);
982    AsyncFunction<X, W> asyncFunction =
983        new AsyncFunction<X, W>() {
984          @Override
985          public ListenableFuture<W> apply(X exception) throws Exception {
986            return closeables.applyAsyncClosingFunction(fallback, exception);
987          }
988
989          @Override
990          public String toString() {
991            return fallback.toString();
992          }
993        };
994    return derive(future.catchingAsync(exceptionType, asyncFunction, executor));
995  }
996
997  /**
998   * Marks this step as the last step in the {@code ClosingFuture} pipeline.
999   *
1000   * <p>The returned {@link Future} is completed when the pipeline's computation completes, or when
1001   * the pipeline is cancelled.
1002   *
1003   * <p>All objects the pipeline has captured for closing will begin to be closed asynchronously
1004   * <b>after</b> the returned {@code Future} is done: the future completes before closing starts,
1005   * rather than once it has finished.
1006   *
1007   * <p>After calling this method, you may not call {@link
1008   * #finishToValueAndCloser(ValueAndCloserConsumer, Executor)}, this method, or any other
1009   * derivation method on the original {@code ClosingFuture} instance.
1010   *
1011   * @return a {@link Future} that represents the final value or exception of the pipeline
1012   */
1013  public FluentFuture<V> finishToFuture() {
1014    if (compareAndUpdateState(OPEN, WILL_CLOSE)) {
1015      logger.get().log(FINER, "will close {0}", this);
1016      future.addListener(
1017          new Runnable() {
1018            @Override
1019            public void run() {
1020              checkAndUpdateState(WILL_CLOSE, CLOSING);
1021              close();
1022              checkAndUpdateState(CLOSING, CLOSED);
1023            }
1024          },
1025          directExecutor());
1026    } else {
1027      switch (state.get()) {
1028        case SUBSUMED:
1029          throw new IllegalStateException(
1030              "Cannot call finishToFuture() after deriving another step");
1031
1032        case WILL_CREATE_VALUE_AND_CLOSER:
1033          throw new IllegalStateException(
1034              "Cannot call finishToFuture() after calling finishToValueAndCloser()");
1035
1036        case WILL_CLOSE:
1037        case CLOSING:
1038        case CLOSED:
1039          throw new IllegalStateException("Cannot call finishToFuture() twice");
1040
1041        case OPEN:
1042          throw new AssertionError();
1043      }
1044    }
1045    return future;
1046  }
1047
1048  /**
1049   * Marks this step as the last step in the {@code ClosingFuture} pipeline. When this step is done,
1050   * {@code receiver} will be called with an object that contains the result of the operation. The
1051   * receiver can store the {@link ValueAndCloser} outside the receiver for later synchronous use.
1052   *
1053   * <p>After calling this method, you may not call {@link #finishToFuture()}, this method again, or
1054   * any other derivation method on the original {@code ClosingFuture} instance.
1055   *
1056   * @param consumer a callback whose method will be called (using {@code executor}) when this
1057   *     operation is done
1058   */
1059  public void finishToValueAndCloser(
1060      final ValueAndCloserConsumer<? super V> consumer, Executor executor) {
1061    checkNotNull(consumer);
1062    if (!compareAndUpdateState(OPEN, WILL_CREATE_VALUE_AND_CLOSER)) {
1063      switch (state.get()) {
1064        case SUBSUMED:
1065          throw new IllegalStateException(
1066              "Cannot call finishToValueAndCloser() after deriving another step");
1067
1068        case WILL_CLOSE:
1069        case CLOSING:
1070        case CLOSED:
1071          throw new IllegalStateException(
1072              "Cannot call finishToValueAndCloser() after calling finishToFuture()");
1073
1074        case WILL_CREATE_VALUE_AND_CLOSER:
1075          throw new IllegalStateException("Cannot call finishToValueAndCloser() twice");
1076
1077        case OPEN:
1078          break;
1079      }
1080      throw new AssertionError(state);
1081    }
1082    future.addListener(
1083        new Runnable() {
1084          @Override
1085          public void run() {
1086            provideValueAndCloser(consumer, ClosingFuture.this);
1087          }
1088        },
1089        executor);
1090  }
1091
1092  private static <C extends @Nullable Object, V extends C> void provideValueAndCloser(
1093      ValueAndCloserConsumer<C> consumer, ClosingFuture<V> closingFuture) {
1094    consumer.accept(new ValueAndCloser<C>(closingFuture));
1095  }
1096
1097  /**
1098   * Attempts to cancel execution of this step. This attempt will fail if the step has already
1099   * completed, has already been cancelled, or could not be cancelled for some other reason. If
1100   * successful, and this step has not started when {@code cancel} is called, this step should never
1101   * run.
1102   *
1103   * <p>If successful, causes the objects captured by this step (if already started) and its input
1104   * step(s) for later closing to be closed on their respective {@link Executor}s. If any such calls
1105   * specified {@link MoreExecutors#directExecutor()}, those objects will be closed synchronously.
1106   *
1107   * @param mayInterruptIfRunning {@code true} if the thread executing this task should be
1108   *     interrupted; otherwise, in-progress tasks are allowed to complete, but the step will be
1109   *     cancelled regardless
1110   * @return {@code false} if the step could not be cancelled, typically because it has already
1111   *     completed normally; {@code true} otherwise
1112   */
1113  @CanIgnoreReturnValue
1114  @SuppressWarnings("Interruption") // We are propagating an interrupt from a caller.
1115  public boolean cancel(boolean mayInterruptIfRunning) {
1116    logger.get().log(FINER, "cancelling {0}", this);
1117    boolean cancelled = future.cancel(mayInterruptIfRunning);
1118    if (cancelled) {
1119      close();
1120    }
1121    return cancelled;
1122  }
1123
1124  private void close() {
1125    logger.get().log(FINER, "closing {0}", this);
1126    closeables.close();
1127  }
1128
1129  private <U extends @Nullable Object> ClosingFuture<U> derive(FluentFuture<U> future) {
1130    ClosingFuture<U> derived = new ClosingFuture<>(future);
1131    becomeSubsumedInto(derived.closeables);
1132    return derived;
1133  }
1134
1135  private void becomeSubsumedInto(CloseableList otherCloseables) {
1136    checkAndUpdateState(OPEN, SUBSUMED);
1137    otherCloseables.add(closeables, directExecutor());
1138  }
1139
1140  /**
1141   * An object that can return the value of the {@link ClosingFuture}s that are passed to {@link
1142   * #whenAllComplete(Iterable)} or {@link #whenAllSucceed(Iterable)}.
1143   *
1144   * <p>Only for use by a {@link CombiningCallable} or {@link AsyncCombiningCallable} object.
1145   */
1146  public static final class Peeker {
1147    private final ImmutableList<ClosingFuture<?>> futures;
1148    private volatile boolean beingCalled;
1149
1150    private Peeker(ImmutableList<ClosingFuture<?>> futures) {
1151      this.futures = checkNotNull(futures);
1152    }
1153
1154    /**
1155     * Returns the value of {@code closingFuture}.
1156     *
1157     * @throws ExecutionException if {@code closingFuture} is a failed step
1158     * @throws CancellationException if the {@code closingFuture}'s future was cancelled
1159     * @throws IllegalArgumentException if {@code closingFuture} is not one of the futures passed to
1160     *     {@link #whenAllComplete(Iterable)} or {@link #whenAllComplete(Iterable)}
1161     * @throws IllegalStateException if called outside of a call to {@link
1162     *     CombiningCallable#call(DeferredCloser, Peeker)} or {@link
1163     *     AsyncCombiningCallable#call(DeferredCloser, Peeker)}
1164     */
1165    @ParametricNullness
1166    public final <D extends @Nullable Object> D getDone(ClosingFuture<D> closingFuture)
1167        throws ExecutionException {
1168      checkState(beingCalled);
1169      checkArgument(futures.contains(closingFuture));
1170      return Futures.getDone(closingFuture.future);
1171    }
1172
1173    @ParametricNullness
1174    private <V extends @Nullable Object> V call(
1175        CombiningCallable<V> combiner, CloseableList closeables) throws Exception {
1176      beingCalled = true;
1177      CloseableList newCloseables = new CloseableList();
1178      try {
1179        return combiner.call(newCloseables.closer, this);
1180      } finally {
1181        closeables.add(newCloseables, directExecutor());
1182        beingCalled = false;
1183      }
1184    }
1185
1186    private <V extends @Nullable Object> FluentFuture<V> callAsync(
1187        AsyncCombiningCallable<V> combiner, CloseableList closeables) throws Exception {
1188      beingCalled = true;
1189      CloseableList newCloseables = new CloseableList();
1190      try {
1191        ClosingFuture<V> closingFuture = combiner.call(newCloseables.closer, this);
1192        closingFuture.becomeSubsumedInto(closeables);
1193        return closingFuture.future;
1194      } finally {
1195        closeables.add(newCloseables, directExecutor());
1196        beingCalled = false;
1197      }
1198    }
1199  }
1200
1201  /**
1202   * A builder of a {@link ClosingFuture} step that is derived from more than one input step.
1203   *
1204   * <p>See {@link #whenAllComplete(Iterable)} and {@link #whenAllSucceed(Iterable)} for how to
1205   * instantiate this class.
1206   *
1207   * <p>Example:
1208   *
1209   * <pre>{@code
1210   * final ClosingFuture<BufferedReader> file1ReaderFuture = ...;
1211   * final ClosingFuture<BufferedReader> file2ReaderFuture = ...;
1212   * ListenableFuture<Integer> numberOfDifferentLines =
1213   *       ClosingFuture.whenAllSucceed(file1ReaderFuture, file2ReaderFuture)
1214   *           .call(
1215   *               (closer, peeker) -> {
1216   *                 BufferedReader file1Reader = peeker.getDone(file1ReaderFuture);
1217   *                 BufferedReader file2Reader = peeker.getDone(file2ReaderFuture);
1218   *                 return countDifferentLines(file1Reader, file2Reader);
1219   *               },
1220   *               executor)
1221   *           .closing(executor);
1222   * }</pre>
1223   */
1224  @DoNotMock("Use ClosingFuture.whenAllSucceed() or .whenAllComplete() instead.")
1225  public static class Combiner {
1226
1227    private final CloseableList closeables = new CloseableList();
1228
1229    /**
1230     * An operation that returns a result and may throw an exception.
1231     *
1232     * @param <V> the type of the result
1233     */
1234    public interface CombiningCallable<V extends @Nullable Object> {
1235      /**
1236       * Computes a result, or throws an exception if unable to do so.
1237       *
1238       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
1239       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
1240       * (but not before this method completes), even if this method throws or the pipeline is
1241       * cancelled.
1242       *
1243       * @param peeker used to get the value of any of the input futures
1244       */
1245      @ParametricNullness
1246      V call(DeferredCloser closer, Peeker peeker) throws Exception;
1247    }
1248
1249    /**
1250     * An operation that returns a {@link ClosingFuture} result and may throw an exception.
1251     *
1252     * @param <V> the type of the result
1253     */
1254    public interface AsyncCombiningCallable<V extends @Nullable Object> {
1255      /**
1256       * Computes a {@link ClosingFuture} result, or throws an exception if unable to do so.
1257       *
1258       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
1259       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
1260       * (but not before this method completes), even if this method throws or the pipeline is
1261       * cancelled.
1262       *
1263       * @param peeker used to get the value of any of the input futures
1264       */
1265      ClosingFuture<V> call(DeferredCloser closer, Peeker peeker) throws Exception;
1266    }
1267
1268    private final boolean allMustSucceed;
1269    protected final ImmutableList<ClosingFuture<?>> inputs;
1270
1271    private Combiner(boolean allMustSucceed, Iterable<? extends ClosingFuture<?>> inputs) {
1272      this.allMustSucceed = allMustSucceed;
1273      this.inputs = ImmutableList.copyOf(inputs);
1274      for (ClosingFuture<?> input : inputs) {
1275        input.becomeSubsumedInto(closeables);
1276      }
1277    }
1278
1279    /**
1280     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
1281     * combining function to their values. The function can use a {@link DeferredCloser} to capture
1282     * objects to be closed when the pipeline is done.
1283     *
1284     * <p>If this combiner was returned by a {@link #whenAllSucceed} method and any of the inputs
1285     * fail, so will the returned step.
1286     *
1287     * <p>If the combiningCallable throws a {@code CancellationException}, the pipeline will be
1288     * cancelled.
1289     *
1290     * <p>If the combiningCallable throws an {@code ExecutionException}, the cause of the thrown
1291     * {@code ExecutionException} will be extracted and used as the failure of the derived step.
1292     */
1293    public <V extends @Nullable Object> ClosingFuture<V> call(
1294        final CombiningCallable<V> combiningCallable, Executor executor) {
1295      Callable<V> callable =
1296          new Callable<V>() {
1297            @Override
1298            @ParametricNullness
1299            public V call() throws Exception {
1300              return new Peeker(inputs).call(combiningCallable, closeables);
1301            }
1302
1303            @Override
1304            public String toString() {
1305              return combiningCallable.toString();
1306            }
1307          };
1308      ClosingFuture<V> derived = new ClosingFuture<>(futureCombiner().call(callable, executor));
1309      derived.closeables.add(closeables, directExecutor());
1310      return derived;
1311    }
1312
1313    /**
1314     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
1315     * {@code ClosingFuture}-returning function to their values. The function can use a {@link
1316     * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
1317     * captured by the returned {@link ClosingFuture}).
1318     *
1319     * <p>If this combiner was returned by a {@link #whenAllSucceed} method and any of the inputs
1320     * fail, so will the returned step.
1321     *
1322     * <p>If the combiningCallable throws a {@code CancellationException}, the pipeline will be
1323     * cancelled.
1324     *
1325     * <p>If the combiningCallable throws an {@code ExecutionException}, the cause of the thrown
1326     * {@code ExecutionException} will be extracted and used as the failure of the derived step.
1327     *
1328     * <p>If the combiningCallable throws any other exception, it will be used as the failure of the
1329     * derived step.
1330     *
1331     * <p>If an exception is thrown after the combiningCallable creates a {@code ClosingFuture},
1332     * then none of the closeable objects in that {@code ClosingFuture} will be closed.
1333     *
1334     * <p>Usage guidelines for this method:
1335     *
1336     * <ul>
1337     *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
1338     *       {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
1339     *       Executor)} instead, with a function that returns the next value directly.
1340     *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
1341     *       for every closeable object this step creates in order to capture it for later closing.
1342     *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
1343     *       ClosingFuture} call {@link #from(ListenableFuture)}.
1344     * </ul>
1345     *
1346     * <p>The same warnings about doing heavyweight operations within {@link
1347     * ClosingFuture#transformAsync(AsyncClosingFunction, Executor)} apply here.
1348     */
1349    public <V extends @Nullable Object> ClosingFuture<V> callAsync(
1350        final AsyncCombiningCallable<V> combiningCallable, Executor executor) {
1351      AsyncCallable<V> asyncCallable =
1352          new AsyncCallable<V>() {
1353            @Override
1354            public ListenableFuture<V> call() throws Exception {
1355              return new Peeker(inputs).callAsync(combiningCallable, closeables);
1356            }
1357
1358            @Override
1359            public String toString() {
1360              return combiningCallable.toString();
1361            }
1362          };
1363      ClosingFuture<V> derived =
1364          new ClosingFuture<>(futureCombiner().callAsync(asyncCallable, executor));
1365      derived.closeables.add(closeables, directExecutor());
1366      return derived;
1367    }
1368
1369    private FutureCombiner<@Nullable Object> futureCombiner() {
1370      return allMustSucceed
1371          ? Futures.whenAllSucceed(inputFutures())
1372          : Futures.whenAllComplete(inputFutures());
1373    }
1374
1375
1376    private ImmutableList<FluentFuture<?>> inputFutures() {
1377      return FluentIterable.from(inputs)
1378          .<FluentFuture<?>>transform(future -> future.future)
1379          .toList();
1380    }
1381  }
1382
1383  /**
1384   * A generic {@link Combiner} that lets you use a lambda or method reference to combine two {@link
1385   * ClosingFuture}s. Use {@link #whenAllSucceed(ClosingFuture, ClosingFuture)} to start this
1386   * combination.
1387   *
1388   * @param <V1> the type returned by the first future
1389   * @param <V2> the type returned by the second future
1390   */
1391  public static final class Combiner2<V1 extends @Nullable Object, V2 extends @Nullable Object>
1392      extends Combiner {
1393
1394    /**
1395     * A function that returns a value when applied to the values of the two futures passed to
1396     * {@link #whenAllSucceed(ClosingFuture, ClosingFuture)}.
1397     *
1398     * @param <V1> the type returned by the first future
1399     * @param <V2> the type returned by the second future
1400     * @param <U> the type returned by the function
1401     */
1402    public interface ClosingFunction2<
1403        V1 extends @Nullable Object, V2 extends @Nullable Object, U extends @Nullable Object> {
1404
1405      /**
1406       * Applies this function to two inputs, or throws an exception if unable to do so.
1407       *
1408       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
1409       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
1410       * (but not before this method completes), even if this method throws or the pipeline is
1411       * cancelled.
1412       */
1413      @ParametricNullness
1414      U apply(DeferredCloser closer, @ParametricNullness V1 value1, @ParametricNullness V2 value2)
1415          throws Exception;
1416    }
1417
1418    /**
1419     * A function that returns a {@link ClosingFuture} when applied to the values of the two futures
1420     * passed to {@link #whenAllSucceed(ClosingFuture, ClosingFuture)}.
1421     *
1422     * @param <V1> the type returned by the first future
1423     * @param <V2> the type returned by the second future
1424     * @param <U> the type returned by the function
1425     */
1426    public interface AsyncClosingFunction2<
1427        V1 extends @Nullable Object, V2 extends @Nullable Object, U extends @Nullable Object> {
1428
1429      /**
1430       * Applies this function to two inputs, or throws an exception if unable to do so.
1431       *
1432       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
1433       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
1434       * (but not before this method completes), even if this method throws or the pipeline is
1435       * cancelled.
1436       */
1437      ClosingFuture<U> apply(
1438          DeferredCloser closer, @ParametricNullness V1 value1, @ParametricNullness V2 value2)
1439          throws Exception;
1440    }
1441
1442    private final ClosingFuture<V1> future1;
1443    private final ClosingFuture<V2> future2;
1444
1445    private Combiner2(ClosingFuture<V1> future1, ClosingFuture<V2> future2) {
1446      super(true, ImmutableList.of(future1, future2));
1447      this.future1 = future1;
1448      this.future2 = future2;
1449    }
1450
1451    /**
1452     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
1453     * combining function to their values. The function can use a {@link DeferredCloser} to capture
1454     * objects to be closed when the pipeline is done.
1455     *
1456     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture)} and
1457     * any of the inputs fail, so will the returned step.
1458     *
1459     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
1460     *
1461     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
1462     * ExecutionException} will be extracted and used as the failure of the derived step.
1463     */
1464    public <U extends @Nullable Object> ClosingFuture<U> call(
1465        final ClosingFunction2<V1, V2, U> function, Executor executor) {
1466      return call(
1467          new CombiningCallable<U>() {
1468            @Override
1469            @ParametricNullness
1470            public U call(DeferredCloser closer, Peeker peeker) throws Exception {
1471              return function.apply(closer, peeker.getDone(future1), peeker.getDone(future2));
1472            }
1473
1474            @Override
1475            public String toString() {
1476              return function.toString();
1477            }
1478          },
1479          executor);
1480    }
1481
1482    /**
1483     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
1484     * {@code ClosingFuture}-returning function to their values. The function can use a {@link
1485     * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
1486     * captured by the returned {@link ClosingFuture}).
1487     *
1488     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture)} and
1489     * any of the inputs fail, so will the returned step.
1490     *
1491     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
1492     *
1493     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
1494     * ExecutionException} will be extracted and used as the failure of the derived step.
1495     *
1496     * <p>If the function throws any other exception, it will be used as the failure of the derived
1497     * step.
1498     *
1499     * <p>If an exception is thrown after the function creates a {@code ClosingFuture}, then none of
1500     * the closeable objects in that {@code ClosingFuture} will be closed.
1501     *
1502     * <p>Usage guidelines for this method:
1503     *
1504     * <ul>
1505     *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
1506     *       {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
1507     *       Executor)} instead, with a function that returns the next value directly.
1508     *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
1509     *       for every closeable object this step creates in order to capture it for later closing.
1510     *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
1511     *       ClosingFuture} call {@link #from(ListenableFuture)}.
1512     * </ul>
1513     *
1514     * <p>The same warnings about doing heavyweight operations within {@link
1515     * ClosingFuture#transformAsync(AsyncClosingFunction, Executor)} apply here.
1516     */
1517    public <U extends @Nullable Object> ClosingFuture<U> callAsync(
1518        final AsyncClosingFunction2<V1, V2, U> function, Executor executor) {
1519      return callAsync(
1520          new AsyncCombiningCallable<U>() {
1521            @Override
1522            public ClosingFuture<U> call(DeferredCloser closer, Peeker peeker) throws Exception {
1523              return function.apply(closer, peeker.getDone(future1), peeker.getDone(future2));
1524            }
1525
1526            @Override
1527            public String toString() {
1528              return function.toString();
1529            }
1530          },
1531          executor);
1532    }
1533  }
1534
1535  /**
1536   * A generic {@link Combiner} that lets you use a lambda or method reference to combine three
1537   * {@link ClosingFuture}s. Use {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
1538   * ClosingFuture)} to start this combination.
1539   *
1540   * @param <V1> the type returned by the first future
1541   * @param <V2> the type returned by the second future
1542   * @param <V3> the type returned by the third future
1543   */
1544  public static final class Combiner3<
1545          V1 extends @Nullable Object, V2 extends @Nullable Object, V3 extends @Nullable Object>
1546      extends Combiner {
1547    /**
1548     * A function that returns a value when applied to the values of the three futures passed to
1549     * {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture)}.
1550     *
1551     * @param <V1> the type returned by the first future
1552     * @param <V2> the type returned by the second future
1553     * @param <V3> the type returned by the third future
1554     * @param <U> the type returned by the function
1555     */
1556    public interface ClosingFunction3<
1557        V1 extends @Nullable Object,
1558        V2 extends @Nullable Object,
1559        V3 extends @Nullable Object,
1560        U extends @Nullable Object> {
1561      /**
1562       * Applies this function to three inputs, or throws an exception if unable to do so.
1563       *
1564       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
1565       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
1566       * (but not before this method completes), even if this method throws or the pipeline is
1567       * cancelled.
1568       */
1569      @ParametricNullness
1570      U apply(
1571          DeferredCloser closer,
1572          @ParametricNullness V1 value1,
1573          @ParametricNullness V2 value2,
1574          @ParametricNullness V3 value3)
1575          throws Exception;
1576    }
1577
1578    /**
1579     * A function that returns a {@link ClosingFuture} when applied to the values of the three
1580     * futures passed to {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture)}.
1581     *
1582     * @param <V1> the type returned by the first future
1583     * @param <V2> the type returned by the second future
1584     * @param <V3> the type returned by the third future
1585     * @param <U> the type returned by the function
1586     */
1587    public interface AsyncClosingFunction3<
1588        V1 extends @Nullable Object,
1589        V2 extends @Nullable Object,
1590        V3 extends @Nullable Object,
1591        U extends @Nullable Object> {
1592      /**
1593       * Applies this function to three inputs, or throws an exception if unable to do so.
1594       *
1595       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
1596       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
1597       * (but not before this method completes), even if this method throws or the pipeline is
1598       * cancelled.
1599       */
1600      ClosingFuture<U> apply(
1601          DeferredCloser closer,
1602          @ParametricNullness V1 value1,
1603          @ParametricNullness V2 value2,
1604          @ParametricNullness V3 value3)
1605          throws Exception;
1606    }
1607
1608    private final ClosingFuture<V1> future1;
1609    private final ClosingFuture<V2> future2;
1610    private final ClosingFuture<V3> future3;
1611
1612    private Combiner3(
1613        ClosingFuture<V1> future1, ClosingFuture<V2> future2, ClosingFuture<V3> future3) {
1614      super(true, ImmutableList.of(future1, future2, future3));
1615      this.future1 = future1;
1616      this.future2 = future2;
1617      this.future3 = future3;
1618    }
1619
1620    /**
1621     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
1622     * combining function to their values. The function can use a {@link DeferredCloser} to capture
1623     * objects to be closed when the pipeline is done.
1624     *
1625     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
1626     * ClosingFuture)} and any of the inputs fail, so will the returned step.
1627     *
1628     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
1629     *
1630     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
1631     * ExecutionException} will be extracted and used as the failure of the derived step.
1632     */
1633    public <U extends @Nullable Object> ClosingFuture<U> call(
1634        final ClosingFunction3<V1, V2, V3, U> function, Executor executor) {
1635      return call(
1636          new CombiningCallable<U>() {
1637            @Override
1638            @ParametricNullness
1639            public U call(DeferredCloser closer, Peeker peeker) throws Exception {
1640              return function.apply(
1641                  closer,
1642                  peeker.getDone(future1),
1643                  peeker.getDone(future2),
1644                  peeker.getDone(future3));
1645            }
1646
1647            @Override
1648            public String toString() {
1649              return function.toString();
1650            }
1651          },
1652          executor);
1653    }
1654
1655    /**
1656     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
1657     * {@code ClosingFuture}-returning function to their values. The function can use a {@link
1658     * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
1659     * captured by the returned {@link ClosingFuture}).
1660     *
1661     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
1662     * ClosingFuture)} and any of the inputs fail, so will the returned step.
1663     *
1664     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
1665     *
1666     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
1667     * ExecutionException} will be extracted and used as the failure of the derived step.
1668     *
1669     * <p>If the function throws any other exception, it will be used as the failure of the derived
1670     * step.
1671     *
1672     * <p>If an exception is thrown after the function creates a {@code ClosingFuture}, then none of
1673     * the closeable objects in that {@code ClosingFuture} will be closed.
1674     *
1675     * <p>Usage guidelines for this method:
1676     *
1677     * <ul>
1678     *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
1679     *       {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
1680     *       Executor)} instead, with a function that returns the next value directly.
1681     *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
1682     *       for every closeable object this step creates in order to capture it for later closing.
1683     *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
1684     *       ClosingFuture} call {@link #from(ListenableFuture)}.
1685     * </ul>
1686     *
1687     * <p>The same warnings about doing heavyweight operations within {@link
1688     * ClosingFuture#transformAsync(AsyncClosingFunction, Executor)} apply here.
1689     */
1690    public <U extends @Nullable Object> ClosingFuture<U> callAsync(
1691        final AsyncClosingFunction3<V1, V2, V3, U> function, Executor executor) {
1692      return callAsync(
1693          new AsyncCombiningCallable<U>() {
1694            @Override
1695            public ClosingFuture<U> call(DeferredCloser closer, Peeker peeker) throws Exception {
1696              return function.apply(
1697                  closer,
1698                  peeker.getDone(future1),
1699                  peeker.getDone(future2),
1700                  peeker.getDone(future3));
1701            }
1702
1703            @Override
1704            public String toString() {
1705              return function.toString();
1706            }
1707          },
1708          executor);
1709    }
1710  }
1711
1712  /**
1713   * A generic {@link Combiner} that lets you use a lambda or method reference to combine four
1714   * {@link ClosingFuture}s. Use {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture,
1715   * ClosingFuture)} to start this combination.
1716   *
1717   * @param <V1> the type returned by the first future
1718   * @param <V2> the type returned by the second future
1719   * @param <V3> the type returned by the third future
1720   * @param <V4> the type returned by the fourth future
1721   */
1722  public static final class Combiner4<
1723          V1 extends @Nullable Object,
1724          V2 extends @Nullable Object,
1725          V3 extends @Nullable Object,
1726          V4 extends @Nullable Object>
1727      extends Combiner {
1728    /**
1729     * A function that returns a value when applied to the values of the four futures passed to
1730     * {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture, ClosingFuture)}.
1731     *
1732     * @param <V1> the type returned by the first future
1733     * @param <V2> the type returned by the second future
1734     * @param <V3> the type returned by the third future
1735     * @param <V4> the type returned by the fourth future
1736     * @param <U> the type returned by the function
1737     */
1738    public interface ClosingFunction4<
1739        V1 extends @Nullable Object,
1740        V2 extends @Nullable Object,
1741        V3 extends @Nullable Object,
1742        V4 extends @Nullable Object,
1743        U extends @Nullable Object> {
1744      /**
1745       * Applies this function to four inputs, or throws an exception if unable to do so.
1746       *
1747       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
1748       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
1749       * (but not before this method completes), even if this method throws or the pipeline is
1750       * cancelled.
1751       */
1752      @ParametricNullness
1753      U apply(
1754          DeferredCloser closer,
1755          @ParametricNullness V1 value1,
1756          @ParametricNullness V2 value2,
1757          @ParametricNullness V3 value3,
1758          @ParametricNullness V4 value4)
1759          throws Exception;
1760    }
1761
1762    /**
1763     * A function that returns a {@link ClosingFuture} when applied to the values of the four
1764     * futures passed to {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture,
1765     * ClosingFuture)}.
1766     *
1767     * @param <V1> the type returned by the first future
1768     * @param <V2> the type returned by the second future
1769     * @param <V3> the type returned by the third future
1770     * @param <V4> the type returned by the fourth future
1771     * @param <U> the type returned by the function
1772     */
1773    public interface AsyncClosingFunction4<
1774        V1 extends @Nullable Object,
1775        V2 extends @Nullable Object,
1776        V3 extends @Nullable Object,
1777        V4 extends @Nullable Object,
1778        U extends @Nullable Object> {
1779      /**
1780       * Applies this function to four inputs, or throws an exception if unable to do so.
1781       *
1782       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
1783       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
1784       * (but not before this method completes), even if this method throws or the pipeline is
1785       * cancelled.
1786       */
1787      ClosingFuture<U> apply(
1788          DeferredCloser closer,
1789          @ParametricNullness V1 value1,
1790          @ParametricNullness V2 value2,
1791          @ParametricNullness V3 value3,
1792          @ParametricNullness V4 value4)
1793          throws Exception;
1794    }
1795
1796    private final ClosingFuture<V1> future1;
1797    private final ClosingFuture<V2> future2;
1798    private final ClosingFuture<V3> future3;
1799    private final ClosingFuture<V4> future4;
1800
1801    private Combiner4(
1802        ClosingFuture<V1> future1,
1803        ClosingFuture<V2> future2,
1804        ClosingFuture<V3> future3,
1805        ClosingFuture<V4> future4) {
1806      super(true, ImmutableList.of(future1, future2, future3, future4));
1807      this.future1 = future1;
1808      this.future2 = future2;
1809      this.future3 = future3;
1810      this.future4 = future4;
1811    }
1812
1813    /**
1814     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
1815     * combining function to their values. The function can use a {@link DeferredCloser} to capture
1816     * objects to be closed when the pipeline is done.
1817     *
1818     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
1819     * ClosingFuture, ClosingFuture)} and any of the inputs fail, so will the returned step.
1820     *
1821     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
1822     *
1823     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
1824     * ExecutionException} will be extracted and used as the failure of the derived step.
1825     */
1826    public <U extends @Nullable Object> ClosingFuture<U> call(
1827        final ClosingFunction4<V1, V2, V3, V4, U> function, Executor executor) {
1828      return call(
1829          new CombiningCallable<U>() {
1830            @Override
1831            @ParametricNullness
1832            public U call(DeferredCloser closer, Peeker peeker) throws Exception {
1833              return function.apply(
1834                  closer,
1835                  peeker.getDone(future1),
1836                  peeker.getDone(future2),
1837                  peeker.getDone(future3),
1838                  peeker.getDone(future4));
1839            }
1840
1841            @Override
1842            public String toString() {
1843              return function.toString();
1844            }
1845          },
1846          executor);
1847    }
1848
1849    /**
1850     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
1851     * {@code ClosingFuture}-returning function to their values. The function can use a {@link
1852     * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
1853     * captured by the returned {@link ClosingFuture}).
1854     *
1855     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
1856     * ClosingFuture, ClosingFuture)} and any of the inputs fail, so will the returned step.
1857     *
1858     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
1859     *
1860     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
1861     * ExecutionException} will be extracted and used as the failure of the derived step.
1862     *
1863     * <p>If the function throws any other exception, it will be used as the failure of the derived
1864     * step.
1865     *
1866     * <p>If an exception is thrown after the function creates a {@code ClosingFuture}, then none of
1867     * the closeable objects in that {@code ClosingFuture} will be closed.
1868     *
1869     * <p>Usage guidelines for this method:
1870     *
1871     * <ul>
1872     *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
1873     *       {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
1874     *       Executor)} instead, with a function that returns the next value directly.
1875     *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
1876     *       for every closeable object this step creates in order to capture it for later closing.
1877     *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
1878     *       ClosingFuture} call {@link #from(ListenableFuture)}.
1879     * </ul>
1880     *
1881     * <p>The same warnings about doing heavyweight operations within {@link
1882     * ClosingFuture#transformAsync(AsyncClosingFunction, Executor)} apply here.
1883     */
1884    public <U extends @Nullable Object> ClosingFuture<U> callAsync(
1885        final AsyncClosingFunction4<V1, V2, V3, V4, U> function, Executor executor) {
1886      return callAsync(
1887          new AsyncCombiningCallable<U>() {
1888            @Override
1889            public ClosingFuture<U> call(DeferredCloser closer, Peeker peeker) throws Exception {
1890              return function.apply(
1891                  closer,
1892                  peeker.getDone(future1),
1893                  peeker.getDone(future2),
1894                  peeker.getDone(future3),
1895                  peeker.getDone(future4));
1896            }
1897
1898            @Override
1899            public String toString() {
1900              return function.toString();
1901            }
1902          },
1903          executor);
1904    }
1905  }
1906
1907  /**
1908   * A generic {@link Combiner} that lets you use a lambda or method reference to combine five
1909   * {@link ClosingFuture}s. Use {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture,
1910   * ClosingFuture, ClosingFuture)} to start this combination.
1911   *
1912   * @param <V1> the type returned by the first future
1913   * @param <V2> the type returned by the second future
1914   * @param <V3> the type returned by the third future
1915   * @param <V4> the type returned by the fourth future
1916   * @param <V5> the type returned by the fifth future
1917   */
1918  public static final class Combiner5<
1919          V1 extends @Nullable Object,
1920          V2 extends @Nullable Object,
1921          V3 extends @Nullable Object,
1922          V4 extends @Nullable Object,
1923          V5 extends @Nullable Object>
1924      extends Combiner {
1925    /**
1926     * A function that returns a value when applied to the values of the five futures passed to
1927     * {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture, ClosingFuture,
1928     * ClosingFuture)}.
1929     *
1930     * @param <V1> the type returned by the first future
1931     * @param <V2> the type returned by the second future
1932     * @param <V3> the type returned by the third future
1933     * @param <V4> the type returned by the fourth future
1934     * @param <V5> the type returned by the fifth future
1935     * @param <U> the type returned by the function
1936     */
1937    public interface ClosingFunction5<
1938        V1 extends @Nullable Object,
1939        V2 extends @Nullable Object,
1940        V3 extends @Nullable Object,
1941        V4 extends @Nullable Object,
1942        V5 extends @Nullable Object,
1943        U extends @Nullable Object> {
1944      /**
1945       * Applies this function to five inputs, or throws an exception if unable to do so.
1946       *
1947       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
1948       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
1949       * (but not before this method completes), even if this method throws or the pipeline is
1950       * cancelled.
1951       */
1952      @ParametricNullness
1953      U apply(
1954          DeferredCloser closer,
1955          @ParametricNullness V1 value1,
1956          @ParametricNullness V2 value2,
1957          @ParametricNullness V3 value3,
1958          @ParametricNullness V4 value4,
1959          @ParametricNullness V5 value5)
1960          throws Exception;
1961    }
1962
1963    /**
1964     * A function that returns a {@link ClosingFuture} when applied to the values of the five
1965     * futures passed to {@link #whenAllSucceed(ClosingFuture, ClosingFuture, ClosingFuture,
1966     * ClosingFuture, ClosingFuture)}.
1967     *
1968     * @param <V1> the type returned by the first future
1969     * @param <V2> the type returned by the second future
1970     * @param <V3> the type returned by the third future
1971     * @param <V4> the type returned by the fourth future
1972     * @param <V5> the type returned by the fifth future
1973     * @param <U> the type returned by the function
1974     */
1975    public interface AsyncClosingFunction5<
1976        V1 extends @Nullable Object,
1977        V2 extends @Nullable Object,
1978        V3 extends @Nullable Object,
1979        V4 extends @Nullable Object,
1980        V5 extends @Nullable Object,
1981        U extends @Nullable Object> {
1982      /**
1983       * Applies this function to five inputs, or throws an exception if unable to do so.
1984       *
1985       * <p>Any objects that are passed to {@link DeferredCloser#eventuallyClose(Object, Executor)
1986       * closer.eventuallyClose()} will be closed when the {@link ClosingFuture} pipeline is done
1987       * (but not before this method completes), even if this method throws or the pipeline is
1988       * cancelled.
1989       */
1990      ClosingFuture<U> apply(
1991          DeferredCloser closer,
1992          @ParametricNullness V1 value1,
1993          @ParametricNullness V2 value2,
1994          @ParametricNullness V3 value3,
1995          @ParametricNullness V4 value4,
1996          @ParametricNullness V5 value5)
1997          throws Exception;
1998    }
1999
2000    private final ClosingFuture<V1> future1;
2001    private final ClosingFuture<V2> future2;
2002    private final ClosingFuture<V3> future3;
2003    private final ClosingFuture<V4> future4;
2004    private final ClosingFuture<V5> future5;
2005
2006    private Combiner5(
2007        ClosingFuture<V1> future1,
2008        ClosingFuture<V2> future2,
2009        ClosingFuture<V3> future3,
2010        ClosingFuture<V4> future4,
2011        ClosingFuture<V5> future5) {
2012      super(true, ImmutableList.of(future1, future2, future3, future4, future5));
2013      this.future1 = future1;
2014      this.future2 = future2;
2015      this.future3 = future3;
2016      this.future4 = future4;
2017      this.future5 = future5;
2018    }
2019
2020    /**
2021     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
2022     * combining function to their values. The function can use a {@link DeferredCloser} to capture
2023     * objects to be closed when the pipeline is done.
2024     *
2025     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
2026     * ClosingFuture, ClosingFuture, ClosingFuture)} and any of the inputs fail, so will the
2027     * returned step.
2028     *
2029     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
2030     *
2031     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
2032     * ExecutionException} will be extracted and used as the failure of the derived step.
2033     */
2034    public <U extends @Nullable Object> ClosingFuture<U> call(
2035        final ClosingFunction5<V1, V2, V3, V4, V5, U> function, Executor executor) {
2036      return call(
2037          new CombiningCallable<U>() {
2038            @Override
2039            @ParametricNullness
2040            public U call(DeferredCloser closer, Peeker peeker) throws Exception {
2041              return function.apply(
2042                  closer,
2043                  peeker.getDone(future1),
2044                  peeker.getDone(future2),
2045                  peeker.getDone(future3),
2046                  peeker.getDone(future4),
2047                  peeker.getDone(future5));
2048            }
2049
2050            @Override
2051            public String toString() {
2052              return function.toString();
2053            }
2054          },
2055          executor);
2056    }
2057
2058    /**
2059     * Returns a new {@code ClosingFuture} pipeline step derived from the inputs by applying a
2060     * {@code ClosingFuture}-returning function to their values. The function can use a {@link
2061     * DeferredCloser} to capture objects to be closed when the pipeline is done (other than those
2062     * captured by the returned {@link ClosingFuture}).
2063     *
2064     * <p>If this combiner was returned by {@link #whenAllSucceed(ClosingFuture, ClosingFuture,
2065     * ClosingFuture, ClosingFuture, ClosingFuture)} and any of the inputs fail, so will the
2066     * returned step.
2067     *
2068     * <p>If the function throws a {@code CancellationException}, the pipeline will be cancelled.
2069     *
2070     * <p>If the function throws an {@code ExecutionException}, the cause of the thrown {@code
2071     * ExecutionException} will be extracted and used as the failure of the derived step.
2072     *
2073     * <p>If the function throws any other exception, it will be used as the failure of the derived
2074     * step.
2075     *
2076     * <p>If an exception is thrown after the function creates a {@code ClosingFuture}, then none of
2077     * the closeable objects in that {@code ClosingFuture} will be closed.
2078     *
2079     * <p>Usage guidelines for this method:
2080     *
2081     * <ul>
2082     *   <li>Use this method only when calling an API that returns a {@link ListenableFuture} or a
2083     *       {@code ClosingFuture}. If possible, prefer calling {@link #call(CombiningCallable,
2084     *       Executor)} instead, with a function that returns the next value directly.
2085     *   <li>Call {@link DeferredCloser#eventuallyClose(Object, Executor) closer.eventuallyClose()}
2086     *       for every closeable object this step creates in order to capture it for later closing.
2087     *   <li>Return a {@code ClosingFuture}. To turn a {@link ListenableFuture} into a {@code
2088     *       ClosingFuture} call {@link #from(ListenableFuture)}.
2089     * </ul>
2090     *
2091     * <p>The same warnings about doing heavyweight operations within {@link
2092     * ClosingFuture#transformAsync(AsyncClosingFunction, Executor)} apply here.
2093     */
2094    public <U extends @Nullable Object> ClosingFuture<U> callAsync(
2095        final AsyncClosingFunction5<V1, V2, V3, V4, V5, U> function, Executor executor) {
2096      return callAsync(
2097          new AsyncCombiningCallable<U>() {
2098            @Override
2099            public ClosingFuture<U> call(DeferredCloser closer, Peeker peeker) throws Exception {
2100              return function.apply(
2101                  closer,
2102                  peeker.getDone(future1),
2103                  peeker.getDone(future2),
2104                  peeker.getDone(future3),
2105                  peeker.getDone(future4),
2106                  peeker.getDone(future5));
2107            }
2108
2109            @Override
2110            public String toString() {
2111              return function.toString();
2112            }
2113          },
2114          executor);
2115    }
2116  }
2117
2118  @Override
2119  public String toString() {
2120    // TODO(dpb): Better toString, in the style of Futures.transform etc.
2121    return toStringHelper(this).add("state", state.get()).addValue(future).toString();
2122  }
2123
2124  @SuppressWarnings({"removal", "Finalize"}) // b/260137033
2125  @Override
2126  protected void finalize() {
2127    if (state.get().equals(OPEN)) {
2128      logger.get().log(SEVERE, "Uh oh! An open ClosingFuture has leaked and will close: {0}", this);
2129      FluentFuture<V> unused = finishToFuture();
2130    }
2131  }
2132
2133  private static void closeQuietly(final @Nullable AutoCloseable closeable, Executor executor) {
2134    if (closeable == null) {
2135      return;
2136    }
2137    try {
2138      executor.execute(
2139          () -> {
2140            try {
2141              closeable.close();
2142            } catch (Exception e) {
2143              /*
2144               * In guava-jre, any kind of Exception may be thrown because `closeable` has type
2145               * `AutoCloseable`.
2146               *
2147               * In guava-android, the only kinds of Exception that may be thrown are
2148               * RuntimeException and IOException because `closeable` has type `Closeable`—except
2149               * that we have to account for sneaky checked exception.
2150               */
2151              restoreInterruptIfIsInterruptedException(e);
2152              logger.get().log(WARNING, "thrown by close()", e);
2153            }
2154          });
2155    } catch (RejectedExecutionException e) {
2156      if (logger.get().isLoggable(WARNING)) {
2157        logger
2158            .get()
2159            .log(
2160                WARNING,
2161                String.format("while submitting close to %s; will close inline", executor),
2162                e);
2163      }
2164      closeQuietly(closeable, directExecutor());
2165    }
2166  }
2167
2168  private void checkAndUpdateState(State oldState, State newState) {
2169    checkState(
2170        compareAndUpdateState(oldState, newState),
2171        "Expected state to be %s, but it was %s",
2172        oldState,
2173        newState);
2174  }
2175
2176  private boolean compareAndUpdateState(State oldState, State newState) {
2177    return state.compareAndSet(oldState, newState);
2178  }
2179
2180  // TODO(dpb): Should we use a pair of ArrayLists instead of an IdentityHashMap?
2181  private static final class CloseableList extends IdentityHashMap<AutoCloseable, Executor>
2182      implements Closeable {
2183    private final DeferredCloser closer = new DeferredCloser(this);
2184    private volatile boolean closed;
2185    private volatile @Nullable CountDownLatch whenClosed;
2186
2187    <V extends @Nullable Object, U extends @Nullable Object>
2188        ListenableFuture<U> applyClosingFunction(
2189            ClosingFunction<? super V, U> transformation, @ParametricNullness V input)
2190            throws Exception {
2191      // TODO(dpb): Consider ways to defer closing without creating a separate CloseableList.
2192      CloseableList newCloseables = new CloseableList();
2193      try {
2194        return immediateFuture(transformation.apply(newCloseables.closer, input));
2195      } finally {
2196        add(newCloseables, directExecutor());
2197      }
2198    }
2199
2200    <V extends @Nullable Object, U extends @Nullable Object>
2201        FluentFuture<U> applyAsyncClosingFunction(
2202            AsyncClosingFunction<V, U> transformation, @ParametricNullness V input)
2203            throws Exception {
2204      // TODO(dpb): Consider ways to defer closing without creating a separate CloseableList.
2205      CloseableList newCloseables = new CloseableList();
2206      try {
2207        ClosingFuture<U> closingFuture = transformation.apply(newCloseables.closer, input);
2208        closingFuture.becomeSubsumedInto(newCloseables);
2209        return closingFuture.future;
2210      } finally {
2211        add(newCloseables, directExecutor());
2212      }
2213    }
2214
2215    @Override
2216    public void close() {
2217      if (closed) {
2218        return;
2219      }
2220      synchronized (this) {
2221        if (closed) {
2222          return;
2223        }
2224        closed = true;
2225      }
2226      for (Map.Entry<AutoCloseable, Executor> entry : entrySet()) {
2227        closeQuietly(entry.getKey(), entry.getValue());
2228      }
2229      clear();
2230      if (whenClosed != null) {
2231        whenClosed.countDown();
2232      }
2233    }
2234
2235    void add(@Nullable AutoCloseable closeable, Executor executor) {
2236      checkNotNull(executor);
2237      if (closeable == null) {
2238        return;
2239      }
2240      synchronized (this) {
2241        if (!closed) {
2242          put(closeable, executor);
2243          return;
2244        }
2245      }
2246      closeQuietly(closeable, executor);
2247    }
2248
2249    /**
2250     * Returns a latch that reaches zero when this objects' deferred closeables have been closed.
2251     */
2252    CountDownLatch whenClosedCountDown() {
2253      if (closed) {
2254        return new CountDownLatch(0);
2255      }
2256      synchronized (this) {
2257        if (closed) {
2258          return new CountDownLatch(0);
2259        }
2260        checkState(whenClosed == null);
2261        return whenClosed = new CountDownLatch(1);
2262      }
2263    }
2264  }
2265
2266  /**
2267   * Returns an object that can be used to wait until this objects' deferred closeables have all had
2268   * {@link Runnable}s that close them submitted to each one's closing {@link Executor}.
2269   */
2270  @VisibleForTesting
2271  CountDownLatch whenClosedCountDown() {
2272    return closeables.whenClosedCountDown();
2273  }
2274
2275  /** The state of a {@link CloseableList}. */
2276  enum State {
2277    /** The {@link CloseableList} has not been subsumed or closed. */
2278    OPEN,
2279
2280    /**
2281     * The {@link CloseableList} has been subsumed into another. It may not be closed or subsumed
2282     * into any other.
2283     */
2284    SUBSUMED,
2285
2286    /**
2287     * Some {@link ListenableFuture} has a callback attached that will close the {@link
2288     * CloseableList}, but it has not yet run. The {@link CloseableList} may not be subsumed.
2289     */
2290    WILL_CLOSE,
2291
2292    /**
2293     * The callback that closes the {@link CloseableList} is running, but it has not completed. The
2294     * {@link CloseableList} may not be subsumed.
2295     */
2296    CLOSING,
2297
2298    /** The {@link CloseableList} has been closed. It may not be further subsumed. */
2299    CLOSED,
2300
2301    /**
2302     * {@link ClosingFuture#finishToValueAndCloser(ValueAndCloserConsumer, Executor)} has been
2303     * called. The step may not be further subsumed, nor may {@link #finishToFuture()} be called.
2304     */
2305    WILL_CREATE_VALUE_AND_CLOSER,
2306  }
2307}