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