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