001/* 002 * Copyright (C) 2007 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.util.concurrent; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018import static com.google.common.util.concurrent.NullnessCasts.uncheckedNull; 019import static com.google.common.util.concurrent.Platform.interruptCurrentThread; 020import static com.google.common.util.concurrent.Platform.rethrowIfErrorOtherThanStackOverflow; 021import static java.lang.Integer.toHexString; 022import static java.lang.System.identityHashCode; 023import static java.util.Objects.requireNonNull; 024import static java.util.concurrent.TimeUnit.MILLISECONDS; 025import static java.util.logging.Level.SEVERE; 026 027import com.google.common.annotations.GwtCompatible; 028import com.google.common.base.Strings; 029import com.google.common.util.concurrent.internal.InternalFutureFailureAccess; 030import com.google.common.util.concurrent.internal.InternalFutures; 031import com.google.errorprone.annotations.CanIgnoreReturnValue; 032import com.google.errorprone.annotations.ForOverride; 033import com.google.j2objc.annotations.ReflectionSupport; 034import com.google.j2objc.annotations.RetainedLocalRef; 035import java.util.concurrent.CancellationException; 036import java.util.concurrent.ExecutionException; 037import java.util.concurrent.Executor; 038import java.util.concurrent.Future; 039import java.util.concurrent.ScheduledFuture; 040import java.util.concurrent.TimeUnit; 041import java.util.concurrent.TimeoutException; 042import org.jspecify.annotations.Nullable; 043 044/** 045 * An abstract implementation of {@link ListenableFuture}, intended for advanced users only. More 046 * common ways to create a {@code ListenableFuture} include instantiating a {@link SettableFuture}, 047 * submitting a task to a {@link ListeningExecutorService}, and deriving a {@code Future} from an 048 * existing one, typically using methods like {@link Futures#transform(ListenableFuture, 049 * com.google.common.base.Function, java.util.concurrent.Executor) Futures.transform} and {@link 050 * Futures#catching(ListenableFuture, Class, com.google.common.base.Function, 051 * java.util.concurrent.Executor) Futures.catching}. 052 * 053 * <p>This class implements all methods in {@code ListenableFuture}. Subclasses should provide a way 054 * to set the result of the computation through the protected methods {@link #set(Object)}, {@link 055 * #setFuture(ListenableFuture)} and {@link #setException(Throwable)}. Subclasses may also override 056 * {@link #afterDone()}, which will be invoked automatically when the future completes. Subclasses 057 * should rarely override other methods. 058 * 059 * @author Sven Mawson 060 * @author Luke Sandberg 061 * @since 1.0 062 */ 063// Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, || 064@SuppressWarnings("ShortCircuitBoolean") 065@GwtCompatible 066/* 067 * TODO(cpovirk): Do we still need @ReflectionSupport on *this* class now that the fields live in 068 * the superclass? Note that Listener (which we also reflect on) still lives here. 069 */ 070@ReflectionSupport(value = ReflectionSupport.Level.FULL) 071public abstract class AbstractFuture<V extends @Nullable Object> extends AbstractFutureState<V> { 072 /* 073 * All static initialization should be performed in AbstractFutureState: AbstractFutureState's 074 * initialization may trigger logging, which may assume that AbstractFuture is initialized. 075 * 076 * TODO(cpovirk): Write a test that asserts that AbstractFuture has no clinit? 077 */ 078 079 /** 080 * Tag interface marking trusted subclasses. This enables some optimizations. The implementation 081 * of this interface must also be an AbstractFuture and must not override or expose for overriding 082 * any of the public methods of ListenableFuture. 083 */ 084 interface Trusted<V extends @Nullable Object> extends ListenableFuture<V> {} 085 086 /** 087 * A less abstract subclass of AbstractFuture. This can be used to optimize setFuture by ensuring 088 * that {@link #get} calls exactly the implementation of {@link AbstractFuture#get}. 089 */ 090 abstract static class TrustedFuture<V extends @Nullable Object> extends AbstractFuture<V> 091 implements Trusted<V> { 092 @CanIgnoreReturnValue 093 @Override 094 @ParametricNullness 095 public final V get() throws InterruptedException, ExecutionException { 096 return super.get(); 097 } 098 099 @CanIgnoreReturnValue 100 @Override 101 @ParametricNullness 102 public final V get(long timeout, TimeUnit unit) 103 throws InterruptedException, ExecutionException, TimeoutException { 104 return super.get(timeout, unit); 105 } 106 107 @Override 108 public final boolean isDone() { 109 return super.isDone(); 110 } 111 112 @Override 113 public final boolean isCancelled() { 114 return super.isCancelled(); 115 } 116 117 @Override 118 public final void addListener(Runnable listener, Executor executor) { 119 super.addListener(listener, executor); 120 } 121 122 @CanIgnoreReturnValue 123 @Override 124 public final boolean cancel(boolean mayInterruptIfRunning) { 125 return super.cancel(mayInterruptIfRunning); 126 } 127 } 128 129 /** Listeners form a Treiber stack through the {@link #listeners} field. */ 130 static final class Listener { 131 static final Listener TOMBSTONE = new Listener(); 132 // null only for TOMBSTONE 133 final @Nullable Runnable task; 134 // null only for TOMBSTONE 135 final @Nullable Executor executor; 136 137 // writes to next are made visible by subsequent CAS's on the listeners field 138 @Nullable Listener next; 139 140 Listener(Runnable task, Executor executor) { 141 this.task = task; 142 this.executor = executor; 143 } 144 145 Listener() { 146 this.task = null; 147 this.executor = null; 148 } 149 } 150 151 /** A special value to represent failure, when {@link #setException} is called successfully. */ 152 private static final class Failure { 153 static final Failure FALLBACK_INSTANCE = 154 new Failure( 155 new Throwable("Failure occurred while trying to finish a future.") { 156 @Override 157 public Throwable fillInStackTrace() { 158 return this; // no stack trace 159 } 160 }); 161 final Throwable exception; 162 163 Failure(Throwable exception) { 164 this.exception = checkNotNull(exception); 165 } 166 } 167 168 /** A special value to represent cancellation and the 'wasInterrupted' bit. */ 169 private static final class Cancellation { 170 // constants to use when GENERATE_CANCELLATION_CAUSES = false 171 static final @Nullable Cancellation CAUSELESS_INTERRUPTED; 172 static final @Nullable Cancellation CAUSELESS_CANCELLED; 173 174 static { 175 if (GENERATE_CANCELLATION_CAUSES) { 176 CAUSELESS_CANCELLED = null; 177 CAUSELESS_INTERRUPTED = null; 178 } else { 179 CAUSELESS_CANCELLED = new Cancellation(false, null); 180 CAUSELESS_INTERRUPTED = new Cancellation(true, null); 181 } 182 } 183 184 final boolean wasInterrupted; 185 final @Nullable Throwable cause; 186 187 Cancellation(boolean wasInterrupted, @Nullable Throwable cause) { 188 this.wasInterrupted = wasInterrupted; 189 this.cause = cause; 190 } 191 } 192 193 /** A special value that encodes the 'setFuture' state. */ 194 private static final class DelegatingToFuture<V extends @Nullable Object> implements Runnable { 195 final AbstractFuture<V> owner; 196 final ListenableFuture<? extends V> future; 197 198 DelegatingToFuture(AbstractFuture<V> owner, ListenableFuture<? extends V> future) { 199 this.owner = owner; 200 this.future = future; 201 } 202 203 @Override 204 public void run() { 205 if (owner.value() != this) { 206 // nothing to do, we must have been cancelled, don't bother inspecting the future. 207 return; 208 } 209 Object valueToSet = getFutureValue(future); 210 if (casValue(owner, this, valueToSet)) { 211 complete( 212 owner, 213 /* 214 * Interruption doesn't propagate through a DelegatingToFuture chain (see 215 * getFutureValue), so don't invoke interruptTask. 216 */ 217 false); 218 } 219 } 220 } 221 222 /** Constructor for use by subclasses. */ 223 protected AbstractFuture() {} 224 225 /** 226 * {@inheritDoc} 227 * 228 * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the 229 * current thread is interrupted during the call, even if the value is already available. 230 * 231 * @throws CancellationException {@inheritDoc} 232 */ 233 @CanIgnoreReturnValue 234 @Override 235 @ParametricNullness 236 public V get(long timeout, TimeUnit unit) 237 throws InterruptedException, TimeoutException, ExecutionException { 238 return Platform.get(this, timeout, unit); 239 } 240 241 /** 242 * {@inheritDoc} 243 * 244 * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the 245 * current thread is interrupted during the call, even if the value is already available. 246 * 247 * @throws CancellationException {@inheritDoc} 248 */ 249 @CanIgnoreReturnValue 250 @Override 251 @ParametricNullness 252 public V get() throws InterruptedException, ExecutionException { 253 return Platform.get(this); 254 } 255 256 /** 257 * Returns the result of this future or throws in case of failure, just like {@link #get()} except 258 * that this method <i>also</i> throws if this future is not done. 259 * 260 * <p>This method computes its result based on the internal state of {@link AbstractFuture}, so it 261 * does not necessarily return the same result as {@link #get()} if {@link #get()} has been 262 * overridden. Thus, it should be called only on instances of {@link Trusted} or from within 263 * {@link #get()} itself. 264 */ 265 @ParametricNullness 266 @SuppressWarnings("nullness") // TODO(b/147136275): Remove once our checker understands & and |. 267 /* 268 * TODO: b/112550045 - Use this from Futures.getDone when applicable? Note the small difference in 269 * failure message between the two at present. 270 */ 271 final V getFromAlreadyDoneTrustedFuture() throws ExecutionException { 272 @RetainedLocalRef Object localValue = value(); 273 if (localValue == null | localValue instanceof DelegatingToFuture) { 274 throw new IllegalStateException("Cannot get() on a pending future."); 275 } 276 return getDoneValue(localValue); 277 } 278 279 /** Unboxes {@code obj}. Assumes that obj is not {@code null} or a {@link DelegatingToFuture}. */ 280 @ParametricNullness 281 @SuppressWarnings("TypeParameterUnusedInFormals") // sorry not sorry 282 static <V extends @Nullable Object> V getDoneValue(Object obj) throws ExecutionException { 283 // While this seems like it might be too branch-y, simple benchmarking proves it to be 284 // unmeasurable (comparing done AbstractFutures with immediateFuture) 285 if (obj instanceof Cancellation) { 286 Cancellation cancellation = (Cancellation) obj; 287 Throwable cause = cancellation.cause; 288 throw cancellationExceptionWithCause("Task was cancelled.", cause); 289 } else if (obj instanceof Failure) { 290 Failure failure = (Failure) obj; 291 Throwable exception = failure.exception; 292 throw new ExecutionException(exception); 293 } else if (obj == NULL) { 294 /* 295 * It's safe to return null because we would only have stored it in the first place if it were 296 * a valid value for V. 297 */ 298 return uncheckedNull(); 299 } else { 300 @SuppressWarnings("unchecked") // this is the only other option 301 V asV = (V) obj; 302 return asV; 303 } 304 } 305 306 /** Returns whether {@code obj} is <b>not</b> an instance of {@code DelegatingToFuture}. */ 307 // This method lets us: 308 // - avoid exposing DelegatingToFuture to the whole package 309 // - avoid fighting with the relative operator precedence of `instanceof` and `!` 310 static boolean notInstanceOfDelegatingToFuture(@Nullable Object obj) { 311 return !(obj instanceof DelegatingToFuture); 312 } 313 314 @Override 315 public boolean isDone() { 316 @RetainedLocalRef Object localValue = value(); 317 return localValue != null & notInstanceOfDelegatingToFuture(localValue); 318 } 319 320 @Override 321 public boolean isCancelled() { 322 @RetainedLocalRef Object localValue = value(); 323 return localValue instanceof Cancellation; 324 } 325 326 /** 327 * {@inheritDoc} 328 * 329 * <p>If a cancellation attempt succeeds on a {@code Future} that had previously been {@linkplain 330 * #setFuture set asynchronously}, then the cancellation will also be propagated to the delegate 331 * {@code Future} that was supplied in the {@code setFuture} call. 332 * 333 * <p>Rather than override this method to perform additional cancellation work or cleanup, 334 * subclasses should override {@link #afterDone}, consulting {@link #isCancelled} and {@link 335 * #wasInterrupted} as necessary. This ensures that the work is done even if the future is 336 * cancelled without a call to {@code cancel}, such as by calling {@code 337 * setFuture(cancelledFuture)}. 338 * 339 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 340 * acquire other locks, risking deadlocks. 341 */ 342 @CanIgnoreReturnValue 343 @Override 344 public boolean cancel(boolean mayInterruptIfRunning) { 345 @RetainedLocalRef Object localValue = value(); 346 boolean rValue = false; 347 if (localValue == null | localValue instanceof DelegatingToFuture) { 348 // Try to delay allocating the exception. At this point we may still lose the CAS, but it is 349 // certainly less likely. 350 Object valueToSet = 351 GENERATE_CANCELLATION_CAUSES 352 ? new Cancellation( 353 mayInterruptIfRunning, new CancellationException("Future.cancel() was called.")) 354 /* 355 * requireNonNull is safe because we've initialized these if 356 * !GENERATE_CANCELLATION_CAUSES. 357 * 358 * TODO(cpovirk): Maybe it would be cleaner to define a CancellationSupplier interface 359 * with two implementations, one that contains causeless Cancellation instances and 360 * the other of which creates new Cancellation instances each time it's called? Yet 361 * another alternative is to fill in a non-null value for each of the fields no matter 362 * what and to just not use it if !GENERATE_CANCELLATION_CAUSES. 363 */ 364 : requireNonNull( 365 mayInterruptIfRunning 366 ? Cancellation.CAUSELESS_INTERRUPTED 367 : Cancellation.CAUSELESS_CANCELLED); 368 AbstractFuture<?> abstractFuture = this; 369 while (true) { 370 if (casValue(abstractFuture, localValue, valueToSet)) { 371 rValue = true; 372 complete(abstractFuture, mayInterruptIfRunning); 373 if (localValue instanceof DelegatingToFuture) { 374 // propagate cancellation to the future set in setfuture, this is racy, and we don't 375 // care if we are successful or not. 376 ListenableFuture<?> futureToPropagateTo = ((DelegatingToFuture) localValue).future; 377 if (futureToPropagateTo instanceof Trusted) { 378 // If the future is a Trusted instance then we specifically avoid calling cancel() 379 // this has 2 benefits 380 // 1. for long chains of futures strung together with setFuture we consume less stack 381 // 2. we avoid allocating Cancellation objects at every level of the cancellation 382 // chain 383 // We can only do this for Trusted, because Trusted implementations of cancel do 384 // nothing but delegate to this method and do not permit user overrides. 385 AbstractFuture<?> trusted = (AbstractFuture<?>) futureToPropagateTo; 386 localValue = trusted.value(); 387 if (localValue == null | localValue instanceof DelegatingToFuture) { 388 abstractFuture = trusted; 389 continue; // loop back up and try to complete the new future 390 } 391 } else { 392 // not a Trusted instance, call cancel directly. 393 futureToPropagateTo.cancel(mayInterruptIfRunning); 394 } 395 } 396 break; 397 } 398 // obj changed, reread 399 localValue = abstractFuture.value(); 400 if (notInstanceOfDelegatingToFuture(localValue)) { 401 // obj cannot be null at this point, because value can only change from null to non-null. 402 // So if value changed (and it did since we lost the CAS), then it cannot be null and 403 // since it isn't a DelegatingToFuture, then the future must be done and we should exit 404 // the loop 405 break; 406 } 407 } 408 } 409 return rValue; 410 } 411 412 /** 413 * Subclasses can override this method to implement interruption of the future's computation. The 414 * method is invoked automatically by a successful call to {@link #cancel(boolean) cancel(true)}. 415 * 416 * <p>The default implementation does nothing. 417 * 418 * <p>This method is likely to be deprecated. Prefer to override {@link #afterDone}, checking 419 * {@link #wasInterrupted} to decide whether to interrupt your task. 420 * 421 * @since 10.0 422 */ 423 protected void interruptTask() {} 424 425 /** 426 * Returns true if this future was cancelled with {@code mayInterruptIfRunning} set to {@code 427 * true}. 428 * 429 * @since 14.0 430 */ 431 protected final boolean wasInterrupted() { 432 @RetainedLocalRef Object localValue = value(); 433 return (localValue instanceof Cancellation) && ((Cancellation) localValue).wasInterrupted; 434 } 435 436 /** 437 * {@inheritDoc} 438 * 439 * @since 10.0 440 */ 441 @Override 442 public void addListener(Runnable listener, Executor executor) { 443 checkNotNull(listener, "Runnable was null."); 444 checkNotNull(executor, "Executor was null."); 445 // Checking isDone and listeners != TOMBSTONE may seem redundant, but our contract for 446 // addListener says that listeners execute 'immediate' if the future isDone(). However, our 447 // protocol for completing a future is to assign the value field (which sets isDone to true) and 448 // then to release waiters, followed by executing afterDone(), followed by releasing listeners. 449 // That means that it is possible to observe that the future isDone and that your listeners 450 // don't execute 'immediately'. By checking isDone here we avoid that. 451 // A corollary to all that is that we don't need to check isDone inside the loop because if we 452 // get into the loop we know that we weren't done when we entered and therefore we aren't under 453 // an obligation to execute 'immediately'. 454 if (!isDone()) { 455 Listener oldHead = listeners(); 456 if (oldHead != Listener.TOMBSTONE) { 457 Listener newNode = new Listener(listener, executor); 458 do { 459 newNode.next = oldHead; 460 if (casListeners(oldHead, newNode)) { 461 return; 462 } 463 oldHead = listeners(); // re-read 464 } while (oldHead != Listener.TOMBSTONE); 465 } 466 } 467 // If we get here then the Listener TOMBSTONE was set, which means the future is done, call 468 // the listener. 469 executeListener(listener, executor); 470 } 471 472 /** 473 * Sets the result of this {@code Future} unless this {@code Future} has already been cancelled or 474 * set (including {@linkplain #setFuture set asynchronously}). When a call to this method returns, 475 * the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> the call was 476 * accepted (in which case it returns {@code true}). If it returns {@code false}, the {@code 477 * Future} may have previously been set asynchronously, in which case its result may not be known 478 * yet. That result, though not yet known, cannot be overridden by a call to a {@code set*} 479 * method, only by a call to {@link #cancel}. 480 * 481 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 482 * acquire other locks, risking deadlocks. 483 * 484 * @param value the value to be used as the result 485 * @return true if the attempt was accepted, completing the {@code Future} 486 */ 487 @CanIgnoreReturnValue 488 protected boolean set(@ParametricNullness V value) { 489 Object valueToSet = value == null ? NULL : value; 490 if (casValue(this, null, valueToSet)) { 491 complete(this, /* callInterruptTask= */ false); 492 return true; 493 } 494 return false; 495 } 496 497 /** 498 * Sets the failed result of this {@code Future} unless this {@code Future} has already been 499 * cancelled or set (including {@linkplain #setFuture set asynchronously}). When a call to this 500 * method returns, the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> 501 * the call was accepted (in which case it returns {@code true}). If it returns {@code false}, the 502 * {@code Future} may have previously been set asynchronously, in which case its result may not be 503 * known yet. That result, though not yet known, cannot be overridden by a call to a {@code set*} 504 * method, only by a call to {@link #cancel}. 505 * 506 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 507 * acquire other locks, risking deadlocks. 508 * 509 * @param throwable the exception to be used as the failed result 510 * @return true if the attempt was accepted, completing the {@code Future} 511 */ 512 @CanIgnoreReturnValue 513 protected boolean setException(Throwable throwable) { 514 Object valueToSet = new Failure(checkNotNull(throwable)); 515 if (casValue(this, null, valueToSet)) { 516 complete(this, /* callInterruptTask= */ false); 517 return true; 518 } 519 return false; 520 } 521 522 /** 523 * Sets the result of this {@code Future} to match the supplied input {@code Future} once the 524 * supplied {@code Future} is done, unless this {@code Future} has already been cancelled or set 525 * (including "set asynchronously," defined below). 526 * 527 * <p>If the supplied future is {@linkplain #isDone done} when this method is called and the call 528 * is accepted, then this future is guaranteed to have been completed with the supplied future by 529 * the time this method returns. If the supplied future is not done and the call is accepted, then 530 * the future will be <i>set asynchronously</i>. Note that such a result, though not yet known, 531 * cannot be overridden by a call to a {@code set*} method, only by a call to {@link #cancel}. 532 * 533 * <p>If the call {@code setFuture(delegate)} is accepted and this {@code Future} is later 534 * cancelled, cancellation will be propagated to {@code delegate}. Additionally, any call to 535 * {@code setFuture} after any cancellation will propagate cancellation to the supplied {@code 536 * Future}. 537 * 538 * <p>Note that, even if the supplied future is cancelled and it causes this future to complete, 539 * it will never trigger interruption behavior. In particular, it will not cause this future to 540 * invoke the {@link #interruptTask} method, and the {@link #wasInterrupted} method will not 541 * return {@code true}. 542 * 543 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 544 * acquire other locks, risking deadlocks. 545 * 546 * @param future the future to delegate to 547 * @return true if the attempt was accepted, indicating that the {@code Future} was not previously 548 * cancelled or set. 549 * @since 19.0 550 */ 551 @CanIgnoreReturnValue 552 @SuppressWarnings("Interruption") // We are propagating an interrupt from a caller. 553 protected boolean setFuture(ListenableFuture<? extends V> future) { 554 checkNotNull(future); 555 @RetainedLocalRef Object localValue = value(); 556 if (localValue == null) { 557 if (future.isDone()) { 558 Object value = getFutureValue(future); 559 if (casValue(this, null, value)) { 560 complete( 561 this, 562 /* 563 * Interruption doesn't propagate through a DelegatingToFuture chain (see 564 * getFutureValue), so don't invoke interruptTask. 565 */ 566 false); 567 return true; 568 } 569 return false; 570 } 571 DelegatingToFuture<V> valueToSet = new DelegatingToFuture<>(this, future); 572 if (casValue(this, null, valueToSet)) { 573 // the listener is responsible for calling completeWithFuture, directExecutor is appropriate 574 // since all we are doing is unpacking a completed future which should be fast. 575 try { 576 future.addListener(valueToSet, DirectExecutor.INSTANCE); 577 } catch (Throwable t) { 578 // Any Exception is either a RuntimeException or sneaky checked exception. 579 // 580 // addListener has thrown an exception! DelegatingToFuture.run can't throw any exceptions 581 // so this must have been caused by addListener itself. The most likely explanation is a 582 // misconfigured mock. Try to switch to Failure. 583 Failure failure; 584 try { 585 failure = new Failure(t); 586 } catch (Exception | Error oomMostLikely) { // sneaky checked exception 587 failure = Failure.FALLBACK_INSTANCE; 588 } 589 // Note: The only way this CAS could fail is if cancel() has raced with us. That is ok. 590 boolean unused = casValue(this, valueToSet, failure); 591 } 592 return true; 593 } 594 localValue = value(); // we lost the cas, fall through and maybe cancel 595 } 596 // The future has already been set to something. If it is cancellation we should cancel the 597 // incoming future. 598 if (localValue instanceof Cancellation) { 599 // we don't care if it fails, this is best-effort. 600 future.cancel(((Cancellation) localValue).wasInterrupted); 601 } 602 return false; 603 } 604 605 /** 606 * Returns a value that satisfies the contract of the {@link #value} field based on the state of 607 * given future. 608 * 609 * <p>This is approximately the inverse of {@link #getDoneValue(Object)} 610 */ 611 private static Object getFutureValue(ListenableFuture<?> future) { 612 if (future instanceof Trusted) { 613 // Break encapsulation for Trusted instances since we know that subclasses cannot override 614 // .get() and therefore this is equivalent to calling .get() and unpacking the exceptions like 615 // we do below (just much faster because it is a single field read instead of a read, several 616 // branches and possibly creating exceptions). 617 Object v = ((AbstractFuture<?>) future).value(); 618 if (v instanceof Cancellation) { 619 // If the other future was interrupted, clear the interrupted bit while preserving the cause 620 // this will make it consistent with how non-trustedfutures work which cannot propagate the 621 // wasInterrupted bit 622 Cancellation c = (Cancellation) v; 623 if (c.wasInterrupted) { 624 v = 625 c.cause != null 626 ? new Cancellation(/* wasInterrupted= */ false, c.cause) 627 : Cancellation.CAUSELESS_CANCELLED; 628 } 629 } 630 // requireNonNull is safe as long as we call this method only on completed futures. 631 return requireNonNull(v); 632 } 633 if (future instanceof InternalFutureFailureAccess) { 634 Throwable throwable = 635 InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future); 636 if (throwable != null) { 637 return new Failure(throwable); 638 } 639 } 640 boolean wasCancelled = future.isCancelled(); 641 // Don't allocate a CancellationException if it's not necessary 642 if (!GENERATE_CANCELLATION_CAUSES & wasCancelled) { 643 /* 644 * requireNonNull is safe because we've initialized CAUSELESS_CANCELLED if 645 * !GENERATE_CANCELLATION_CAUSES. 646 */ 647 return requireNonNull(Cancellation.CAUSELESS_CANCELLED); 648 } 649 // Otherwise calculate the value by calling .get() 650 try { 651 Object v = getUninterruptibly(future); 652 if (wasCancelled) { 653 return new Cancellation( 654 false, 655 new IllegalArgumentException( 656 "get() did not throw CancellationException, despite reporting " 657 + "isCancelled() == true: " 658 + future)); 659 } 660 return v == null ? NULL : v; 661 } catch (ExecutionException exception) { 662 if (wasCancelled) { 663 return new Cancellation( 664 false, 665 new IllegalArgumentException( 666 "get() did not throw CancellationException, despite reporting " 667 + "isCancelled() == true: " 668 + future, 669 exception)); 670 } 671 return new Failure(exception.getCause()); 672 } catch (CancellationException cancellation) { 673 if (!wasCancelled) { 674 return new Failure( 675 new IllegalArgumentException( 676 "get() threw CancellationException, despite reporting isCancelled() == false: " 677 + future, 678 cancellation)); 679 } 680 return new Cancellation(false, cancellation); 681 } catch (Exception | Error t) { // sneaky checked exception 682 return new Failure(t); 683 } 684 } 685 686 /** 687 * An inlined private copy of {@link Uninterruptibles#getUninterruptibly} used to break an 688 * internal dependency on other /util/concurrent classes. 689 */ 690 @ParametricNullness 691 private static <V extends @Nullable Object> V getUninterruptibly(Future<V> future) 692 throws ExecutionException { 693 boolean interrupted = false; 694 try { 695 while (true) { 696 try { 697 return future.get(); 698 } catch (InterruptedException e) { 699 interrupted = true; 700 } 701 } 702 } finally { 703 if (interrupted) { 704 interruptCurrentThread(); 705 } 706 } 707 } 708 709 /** Unblocks all threads and runs all listeners. */ 710 private static void complete(AbstractFuture<?> param, boolean callInterruptTask) { 711 // Declare a "true" local variable so that the Checker Framework will infer nullness. 712 AbstractFuture<?> future = param; 713 714 Listener next = null; 715 outer: 716 while (true) { 717 future.releaseWaiters(); 718 /* 719 * We call interruptTask() immediately before afterDone() so that migrating between the two 720 * can be a no-op. 721 */ 722 if (callInterruptTask) { 723 future.interruptTask(); 724 /* 725 * Interruption doesn't propagate through a DelegatingToFuture chain (see getFutureValue), 726 * so don't invoke interruptTask on any subsequent futures. 727 */ 728 callInterruptTask = false; 729 } 730 // We call this before the listeners in order to avoid needing to manage a separate stack data 731 // structure for them. Also, some implementations rely on this running prior to listeners 732 // so that the cleanup work is visible to listeners. 733 // afterDone() should be generally fast and only used for cleanup work... but in theory can 734 // also be recursive and create StackOverflowErrors 735 future.afterDone(); 736 // push the current set of listeners onto next 737 next = future.clearListeners(next); 738 future = null; 739 while (next != null) { 740 Listener curr = next; 741 next = next.next; 742 /* 743 * requireNonNull is safe because the listener stack never contains TOMBSTONE until after 744 * clearListeners. 745 */ 746 Runnable task = requireNonNull(curr.task); 747 if (task instanceof DelegatingToFuture) { 748 DelegatingToFuture<?> setFuture = (DelegatingToFuture<?>) task; 749 // We unwind setFuture specifically to avoid StackOverflowErrors in the case of long 750 // chains of DelegatingToFutures 751 // Handling this special case is important because there is no way to pass an executor to 752 // setFuture, so a user couldn't break the chain by doing this themselves. It is also 753 // potentially common if someone writes a recursive Futures.transformAsync transformer. 754 future = setFuture.owner; 755 if (future.value() == setFuture) { 756 Object valueToSet = getFutureValue(setFuture.future); 757 if (casValue(future, setFuture, valueToSet)) { 758 continue outer; 759 } 760 } 761 // otherwise the future we were trying to set is already done. 762 } else { 763 /* 764 * requireNonNull is safe because the listener stack never contains TOMBSTONE until after 765 * clearListeners. 766 */ 767 executeListener(task, requireNonNull(curr.executor)); 768 } 769 } 770 break; 771 } 772 } 773 774 /** 775 * Callback method that is called exactly once after the future is completed. 776 * 777 * <p>If {@link #interruptTask} is also run during completion, {@link #afterDone} runs after it. 778 * 779 * <p>The default implementation of this method in {@code AbstractFuture} does nothing. This is 780 * intended for very lightweight cleanup work, for example, timing statistics or clearing fields. 781 * If your task does anything heavier consider, just using a listener with an executor. 782 * 783 * @since 20.0 784 */ 785 @ForOverride 786 protected void afterDone() {} 787 788 // TODO(b/114236866): Inherit doc from InternalFutureFailureAccess. Also, -link to its URL. 789 /** 790 * Usually returns {@code null} but, if this {@code Future} has failed, may <i>optionally</i> 791 * return the cause of the failure. "Failure" means specifically "completed with an exception"; it 792 * does not include "was cancelled." To be explicit: If this method returns a non-null value, 793 * then: 794 * 795 * <ul> 796 * <li>{@code isDone()} must return {@code true} 797 * <li>{@code isCancelled()} must return {@code false} 798 * <li>{@code get()} must not block, and it must throw an {@code ExecutionException} with the 799 * return value of this method as its cause 800 * </ul> 801 * 802 * <p>This method is {@code protected} so that classes like {@code 803 * com.google.common.util.concurrent.SettableFuture} do not expose it to their users as an 804 * instance method. In the unlikely event that you need to call this method, call {@link 805 * InternalFutures#tryInternalFastPathGetFailure(InternalFutureFailureAccess)}. 806 * 807 * @since 27.0 808 */ 809 @Override 810 /* 811 * We should annotate the superclass, InternalFutureFailureAccess, to say that its copy of this 812 * method returns @Nullable, too. However, we're not sure if we want to make any changes to that 813 * class, since it's in a separate artifact that we planned to release only a single version of. 814 */ 815 protected final @Nullable Throwable tryInternalFastPathGetFailure() { 816 if (this instanceof Trusted) { 817 @RetainedLocalRef Object localValue = value(); 818 if (localValue instanceof Failure) { 819 return ((Failure) localValue).exception; 820 } 821 } 822 return null; 823 } 824 825 /** 826 * If this future has been cancelled (and possibly interrupted), cancels (and possibly interrupts) 827 * the given future (if available). 828 */ 829 @SuppressWarnings("nullness") // TODO(b/147136275): Remove once our checker understands & and |. 830 final void maybePropagateCancellationTo(@Nullable Future<?> related) { 831 if (related != null & isCancelled()) { 832 related.cancel(wasInterrupted()); 833 } 834 } 835 836 /** 837 * Clears the {@link #listeners} list and prepends its contents to {@code onto}, least recently 838 * added first. 839 */ 840 private @Nullable Listener clearListeners(@Nullable Listener onto) { 841 // We need to 842 // 1. atomically swap the listeners with TOMBSTONE, this is because addListener uses that 843 // to synchronize with us 844 // 2. reverse the linked list, because despite our rather clear contract, people depend on us 845 // executing listeners in the order they were added 846 // 3. push all the items onto 'onto' and return the new head of the stack 847 Listener head = gasListeners(Listener.TOMBSTONE); 848 Listener reversedList = onto; 849 while (head != null) { 850 Listener tmp = head; 851 head = head.next; 852 tmp.next = reversedList; 853 reversedList = tmp; 854 } 855 return reversedList; 856 } 857 858 // TODO(user): move parts into a default method on ListenableFuture? 859 @Override 860 public String toString() { 861 // TODO(cpovirk): Presize to something plausible? 862 StringBuilder builder = new StringBuilder(); 863 if (getClass().getName().startsWith("com.google.common.util.concurrent.")) { 864 builder.append(getClass().getSimpleName()); 865 } else { 866 builder.append(getClass().getName()); 867 } 868 builder.append('@').append(toHexString(identityHashCode(this))).append("[status="); 869 if (isCancelled()) { 870 builder.append("CANCELLED"); 871 } else if (isDone()) { 872 addDoneString(builder); 873 } else { 874 addPendingString(builder); // delegates to addDoneString if future completes midway 875 } 876 return builder.append("]").toString(); 877 } 878 879 /** 880 * Provide a human-readable explanation of why this future has not yet completed. 881 * 882 * @return null if an explanation cannot be provided (e.g. because the future is done). 883 * @since 23.0 884 */ 885 protected @Nullable String pendingToString() { 886 // TODO(diamondm) consider moving this into addPendingString so it's always in the output 887 if (this instanceof ScheduledFuture) { 888 return "remaining delay=[" + ((ScheduledFuture) this).getDelay(MILLISECONDS) + " ms]"; 889 } 890 return null; 891 } 892 893 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 894 private void addPendingString(StringBuilder builder) { 895 // Capture current builder length so it can be truncated if this future ends up completing while 896 // the toString is being calculated 897 int truncateLength = builder.length(); 898 899 builder.append("PENDING"); 900 901 @RetainedLocalRef Object localValue = value(); 902 if (localValue instanceof DelegatingToFuture) { 903 builder.append(", setFuture=["); 904 appendUserObject(builder, ((DelegatingToFuture) localValue).future); 905 builder.append("]"); 906 } else { 907 String pendingDescription; 908 try { 909 pendingDescription = Strings.emptyToNull(pendingToString()); 910 } catch (Throwable e) { 911 /* 912 * We want to catch (Exception | StackOverflowError), but we can't under environments where 913 * StackOverflowError doesn't exist. 914 */ 915 rethrowIfErrorOtherThanStackOverflow(e); 916 // The Throwable is either a RuntimeException, an Error, or sneaky checked exception. 917 // 918 // Don't call getMessage or toString() on the exception, in case the exception thrown by the 919 // subclass is implemented with bugs similar to the subclass. 920 pendingDescription = "Exception thrown from implementation: " + e.getClass(); 921 } 922 if (pendingDescription != null) { 923 builder.append(", info=[").append(pendingDescription).append("]"); 924 } 925 } 926 927 // The future may complete while calculating the toString, so we check once more to see if the 928 // future is done 929 if (isDone()) { 930 // Truncate anything that was appended before realizing this future is done 931 builder.delete(truncateLength, builder.length()); 932 addDoneString(builder); 933 } 934 } 935 936 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 937 private void addDoneString(StringBuilder builder) { 938 try { 939 V value = getUninterruptibly(this); 940 builder.append("SUCCESS, result=["); 941 appendResultObject(builder, value); 942 builder.append("]"); 943 } catch (ExecutionException e) { 944 builder.append("FAILURE, cause=[").append(e.getCause()).append("]"); 945 } catch (CancellationException e) { 946 builder.append("CANCELLED"); // shouldn't be reachable 947 } catch (Exception e) { // sneaky checked exception 948 builder.append("UNKNOWN, cause=[").append(e.getClass()).append(" thrown from get()]"); 949 } 950 } 951 952 /** 953 * Any object can be the result of a Future, and not every object has a reasonable toString() 954 * implementation. Using a reconstruction of the default Object.toString() prevents OOMs and stack 955 * overflows, and helps avoid sensitive data inadvertently ending up in exception messages. 956 */ 957 private void appendResultObject(StringBuilder builder, @Nullable Object o) { 958 if (o == null) { 959 builder.append("null"); 960 } else if (o == this) { 961 builder.append("this future"); 962 } else { 963 builder 964 .append(o.getClass().getName()) 965 .append("@") 966 .append(Integer.toHexString(System.identityHashCode(o))); 967 } 968 } 969 970 /** Helper for printing user supplied objects into our toString method. */ 971 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 972 private void appendUserObject(StringBuilder builder, @Nullable Object o) { 973 // This is some basic recursion detection for when people create cycles via set/setFuture or 974 // when deep chains of futures exist resulting in a StackOverflowError. We could detect 975 // arbitrary cycles using a thread local but this should be a good enough solution (it is also 976 // what jdk collections do in these cases) 977 try { 978 if (o == this) { 979 builder.append("this future"); 980 } else { 981 builder.append(o); 982 } 983 } catch (Throwable e) { 984 /* 985 * We want to catch (Exception | StackOverflowError), but we can't under environments where 986 * StackOverflowError doesn't exist. 987 */ 988 rethrowIfErrorOtherThanStackOverflow(e); 989 // The Throwable is either a RuntimeException, an Error, or sneaky checked exception. 990 // 991 // Don't call getMessage or toString() on the exception, in case the exception thrown by the 992 // user object is implemented with bugs similar to the user object. 993 builder.append("Exception thrown from implementation: ").append(e.getClass()); 994 } 995 } 996 997 /** 998 * Submits the given runnable to the given {@link Executor} catching and logging all {@linkplain 999 * RuntimeException runtime exceptions} thrown by the executor. 1000 */ 1001 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 1002 private static void executeListener(Runnable runnable, Executor executor) { 1003 try { 1004 executor.execute(runnable); 1005 } catch (Exception e) { // sneaky checked exception 1006 // Log it and keep going -- bad runnable and/or executor. Don't punish the other runnables if 1007 // we're given a bad one. We only catch Exception because we want Errors to propagate up. 1008 log.get() 1009 .log( 1010 SEVERE, 1011 "RuntimeException while executing runnable " 1012 + runnable 1013 + " with executor " 1014 + executor, 1015 e); 1016 } 1017 } 1018 1019 private static CancellationException cancellationExceptionWithCause( 1020 String message, @Nullable Throwable cause) { 1021 CancellationException exception = new CancellationException(message); 1022 exception.initCause(cause); 1023 return exception; 1024 } 1025}