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