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