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