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 @ParametricNullness 257 @SuppressWarnings("nullness") // TODO(b/147136275): Remove once our checker understands & and |. 258 final V getFromAlreadyDoneFuture() throws ExecutionException { 259 @RetainedLocalRef Object localValue = value(); 260 if (localValue == null | localValue instanceof DelegatingToFuture) { 261 throw new IllegalStateException("Cannot get() on a pending future."); 262 } 263 return getDoneValue(localValue); 264 } 265 266 /** Unboxes {@code obj}. Assumes that obj is not {@code null} or a {@link DelegatingToFuture}. */ 267 @ParametricNullness 268 @SuppressWarnings("TypeParameterUnusedInFormals") // sorry not sorry 269 static <V extends @Nullable Object> V getDoneValue(Object obj) throws ExecutionException { 270 // While this seems like it might be too branch-y, simple benchmarking proves it to be 271 // unmeasurable (comparing done AbstractFutures with immediateFuture) 272 if (obj instanceof Cancellation) { 273 Cancellation cancellation = (Cancellation) obj; 274 Throwable cause = cancellation.cause; 275 throw cancellationExceptionWithCause("Task was cancelled.", cause); 276 } else if (obj instanceof Failure) { 277 Failure failure = (Failure) obj; 278 Throwable exception = failure.exception; 279 throw new ExecutionException(exception); 280 } else if (obj == NULL) { 281 /* 282 * It's safe to return null because we would only have stored it in the first place if it were 283 * a valid value for V. 284 */ 285 return uncheckedNull(); 286 } else { 287 @SuppressWarnings("unchecked") // this is the only other option 288 V asV = (V) obj; 289 return asV; 290 } 291 } 292 293 /** Returns whether {@code obj} is <b>not</b> an instance of {@code DelegatingToFuture}. */ 294 // This method lets us: 295 // - avoid exposing DelegatingToFuture to the whole package 296 // - avoid fighting with the relative operator precedence of `instanceof` and `!` 297 static boolean notInstanceOfDelegatingToFuture(@Nullable Object obj) { 298 return !(obj instanceof DelegatingToFuture); 299 } 300 301 @Override 302 public boolean isDone() { 303 @RetainedLocalRef Object localValue = value(); 304 return localValue != null & notInstanceOfDelegatingToFuture(localValue); 305 } 306 307 @Override 308 public boolean isCancelled() { 309 @RetainedLocalRef Object localValue = value(); 310 return localValue instanceof Cancellation; 311 } 312 313 /** 314 * {@inheritDoc} 315 * 316 * <p>If a cancellation attempt succeeds on a {@code Future} that had previously been {@linkplain 317 * #setFuture set asynchronously}, then the cancellation will also be propagated to the delegate 318 * {@code Future} that was supplied in the {@code setFuture} call. 319 * 320 * <p>Rather than override this method to perform additional cancellation work or cleanup, 321 * subclasses should override {@link #afterDone}, consulting {@link #isCancelled} and {@link 322 * #wasInterrupted} as necessary. This ensures that the work is done even if the future is 323 * cancelled without a call to {@code cancel}, such as by calling {@code 324 * setFuture(cancelledFuture)}. 325 * 326 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 327 * acquire other locks, risking deadlocks. 328 */ 329 @CanIgnoreReturnValue 330 @Override 331 public boolean cancel(boolean mayInterruptIfRunning) { 332 @RetainedLocalRef Object localValue = value(); 333 boolean rValue = false; 334 if (localValue == null | localValue instanceof DelegatingToFuture) { 335 // Try to delay allocating the exception. At this point we may still lose the CAS, but it is 336 // certainly less likely. 337 Object valueToSet = 338 GENERATE_CANCELLATION_CAUSES 339 ? new Cancellation( 340 mayInterruptIfRunning, new CancellationException("Future.cancel() was called.")) 341 /* 342 * requireNonNull is safe because we've initialized these if 343 * !GENERATE_CANCELLATION_CAUSES. 344 * 345 * TODO(cpovirk): Maybe it would be cleaner to define a CancellationSupplier interface 346 * with two implementations, one that contains causeless Cancellation instances and 347 * the other of which creates new Cancellation instances each time it's called? Yet 348 * another alternative is to fill in a non-null value for each of the fields no matter 349 * what and to just not use it if !GENERATE_CANCELLATION_CAUSES. 350 */ 351 : requireNonNull( 352 mayInterruptIfRunning 353 ? Cancellation.CAUSELESS_INTERRUPTED 354 : Cancellation.CAUSELESS_CANCELLED); 355 AbstractFuture<?> abstractFuture = this; 356 while (true) { 357 if (casValue(abstractFuture, localValue, valueToSet)) { 358 rValue = true; 359 complete(abstractFuture, mayInterruptIfRunning); 360 if (localValue instanceof DelegatingToFuture) { 361 // propagate cancellation to the future set in setfuture, this is racy, and we don't 362 // care if we are successful or not. 363 ListenableFuture<?> futureToPropagateTo = ((DelegatingToFuture) localValue).future; 364 if (futureToPropagateTo instanceof Trusted) { 365 // If the future is a Trusted instance then we specifically avoid calling cancel() 366 // this has 2 benefits 367 // 1. for long chains of futures strung together with setFuture we consume less stack 368 // 2. we avoid allocating Cancellation objects at every level of the cancellation 369 // chain 370 // We can only do this for Trusted, because Trusted implementations of cancel do 371 // nothing but delegate to this method and do not permit user overrides. 372 AbstractFuture<?> trusted = (AbstractFuture<?>) futureToPropagateTo; 373 localValue = trusted.value(); 374 if (localValue == null | localValue instanceof DelegatingToFuture) { 375 abstractFuture = trusted; 376 continue; // loop back up and try to complete the new future 377 } 378 } else { 379 // not a Trusted instance, call cancel directly. 380 futureToPropagateTo.cancel(mayInterruptIfRunning); 381 } 382 } 383 break; 384 } 385 // obj changed, reread 386 localValue = abstractFuture.value(); 387 if (notInstanceOfDelegatingToFuture(localValue)) { 388 // obj cannot be null at this point, because value can only change from null to non-null. 389 // So if value changed (and it did since we lost the CAS), then it cannot be null and 390 // since it isn't a DelegatingToFuture, then the future must be done and we should exit 391 // the loop 392 break; 393 } 394 } 395 } 396 return rValue; 397 } 398 399 /** 400 * Subclasses can override this method to implement interruption of the future's computation. The 401 * method is invoked automatically by a successful call to {@link #cancel(boolean) cancel(true)}. 402 * 403 * <p>The default implementation does nothing. 404 * 405 * <p>This method is likely to be deprecated. Prefer to override {@link #afterDone}, checking 406 * {@link #wasInterrupted} to decide whether to interrupt your task. 407 * 408 * @since 10.0 409 */ 410 protected void interruptTask() {} 411 412 /** 413 * Returns true if this future was cancelled with {@code mayInterruptIfRunning} set to {@code 414 * true}. 415 * 416 * @since 14.0 417 */ 418 protected final boolean wasInterrupted() { 419 @RetainedLocalRef Object localValue = value(); 420 return (localValue instanceof Cancellation) && ((Cancellation) localValue).wasInterrupted; 421 } 422 423 /** 424 * {@inheritDoc} 425 * 426 * @since 10.0 427 */ 428 @Override 429 public void addListener(Runnable listener, Executor executor) { 430 checkNotNull(listener, "Runnable was null."); 431 checkNotNull(executor, "Executor was null."); 432 // Checking isDone and listeners != TOMBSTONE may seem redundant, but our contract for 433 // addListener says that listeners execute 'immediate' if the future isDone(). However, our 434 // protocol for completing a future is to assign the value field (which sets isDone to true) and 435 // then to release waiters, followed by executing afterDone(), followed by releasing listeners. 436 // That means that it is possible to observe that the future isDone and that your listeners 437 // don't execute 'immediately'. By checking isDone here we avoid that. 438 // A corollary to all that is that we don't need to check isDone inside the loop because if we 439 // get into the loop we know that we weren't done when we entered and therefore we aren't under 440 // an obligation to execute 'immediately'. 441 if (!isDone()) { 442 Listener oldHead = listeners(); 443 if (oldHead != Listener.TOMBSTONE) { 444 Listener newNode = new Listener(listener, executor); 445 do { 446 newNode.next = oldHead; 447 if (casListeners(oldHead, newNode)) { 448 return; 449 } 450 oldHead = listeners(); // re-read 451 } while (oldHead != Listener.TOMBSTONE); 452 } 453 } 454 // If we get here then the Listener TOMBSTONE was set, which means the future is done, call 455 // the listener. 456 executeListener(listener, executor); 457 } 458 459 /** 460 * Sets the result of this {@code Future} unless this {@code Future} has already been cancelled or 461 * set (including {@linkplain #setFuture set asynchronously}). When a call to this method returns, 462 * the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> the call was 463 * accepted (in which case it returns {@code true}). If it returns {@code false}, the {@code 464 * Future} may have previously been set asynchronously, in which case its result may not be known 465 * yet. That result, though not yet known, cannot be overridden by a call to a {@code set*} 466 * method, only by a call to {@link #cancel}. 467 * 468 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 469 * acquire other locks, risking deadlocks. 470 * 471 * @param value the value to be used as the result 472 * @return true if the attempt was accepted, completing the {@code Future} 473 */ 474 @CanIgnoreReturnValue 475 protected boolean set(@ParametricNullness V value) { 476 Object valueToSet = value == null ? NULL : value; 477 if (casValue(this, null, valueToSet)) { 478 complete(this, /* callInterruptTask= */ false); 479 return true; 480 } 481 return false; 482 } 483 484 /** 485 * Sets the failed result of this {@code Future} unless this {@code Future} has already been 486 * cancelled or set (including {@linkplain #setFuture set asynchronously}). When a call to this 487 * method returns, the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> 488 * the call was accepted (in which case it returns {@code true}). If it returns {@code false}, the 489 * {@code Future} may have previously been set asynchronously, in which case its result may not be 490 * known yet. That result, though not yet known, cannot be overridden by a call to a {@code set*} 491 * method, only by a call to {@link #cancel}. 492 * 493 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 494 * acquire other locks, risking deadlocks. 495 * 496 * @param throwable the exception to be used as the failed result 497 * @return true if the attempt was accepted, completing the {@code Future} 498 */ 499 @CanIgnoreReturnValue 500 protected boolean setException(Throwable throwable) { 501 Object valueToSet = new Failure(checkNotNull(throwable)); 502 if (casValue(this, null, valueToSet)) { 503 complete(this, /* callInterruptTask= */ false); 504 return true; 505 } 506 return false; 507 } 508 509 /** 510 * Sets the result of this {@code Future} to match the supplied input {@code Future} once the 511 * supplied {@code Future} is done, unless this {@code Future} has already been cancelled or set 512 * (including "set asynchronously," defined below). 513 * 514 * <p>If the supplied future is {@linkplain #isDone done} when this method is called and the call 515 * is accepted, then this future is guaranteed to have been completed with the supplied future by 516 * the time this method returns. If the supplied future is not done and the call is accepted, then 517 * the future will be <i>set asynchronously</i>. Note that such a result, though not yet known, 518 * cannot be overridden by a call to a {@code set*} method, only by a call to {@link #cancel}. 519 * 520 * <p>If the call {@code setFuture(delegate)} is accepted and this {@code Future} is later 521 * cancelled, cancellation will be propagated to {@code delegate}. Additionally, any call to 522 * {@code setFuture} after any cancellation will propagate cancellation to the supplied {@code 523 * Future}. 524 * 525 * <p>Note that, even if the supplied future is cancelled and it causes this future to complete, 526 * it will never trigger interruption behavior. In particular, it will not cause this future to 527 * invoke the {@link #interruptTask} method, and the {@link #wasInterrupted} method will not 528 * return {@code true}. 529 * 530 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 531 * acquire other locks, risking deadlocks. 532 * 533 * @param future the future to delegate to 534 * @return true if the attempt was accepted, indicating that the {@code Future} was not previously 535 * cancelled or set. 536 * @since 19.0 537 */ 538 @CanIgnoreReturnValue 539 @SuppressWarnings("Interruption") // We are propagating an interrupt from a caller. 540 protected boolean setFuture(ListenableFuture<? extends V> future) { 541 checkNotNull(future); 542 @RetainedLocalRef Object localValue = value(); 543 if (localValue == null) { 544 if (future.isDone()) { 545 Object value = getFutureValue(future); 546 if (casValue(this, null, value)) { 547 complete( 548 this, 549 /* 550 * Interruption doesn't propagate through a DelegatingToFuture chain (see 551 * getFutureValue), so don't invoke interruptTask. 552 */ 553 false); 554 return true; 555 } 556 return false; 557 } 558 DelegatingToFuture<V> valueToSet = new DelegatingToFuture<>(this, future); 559 if (casValue(this, null, valueToSet)) { 560 // the listener is responsible for calling completeWithFuture, directExecutor is appropriate 561 // since all we are doing is unpacking a completed future which should be fast. 562 try { 563 future.addListener(valueToSet, DirectExecutor.INSTANCE); 564 } catch (Throwable t) { 565 // Any Exception is either a RuntimeException or sneaky checked exception. 566 // 567 // addListener has thrown an exception! DelegatingToFuture.run can't throw any exceptions 568 // so this must have been caused by addListener itself. The most likely explanation is a 569 // misconfigured mock. Try to switch to Failure. 570 Failure failure; 571 try { 572 failure = new Failure(t); 573 } catch (Exception | Error oomMostLikely) { // sneaky checked exception 574 failure = Failure.FALLBACK_INSTANCE; 575 } 576 // Note: The only way this CAS could fail is if cancel() has raced with us. That is ok. 577 boolean unused = casValue(this, valueToSet, failure); 578 } 579 return true; 580 } 581 localValue = value(); // we lost the cas, fall through and maybe cancel 582 } 583 // The future has already been set to something. If it is cancellation we should cancel the 584 // incoming future. 585 if (localValue instanceof Cancellation) { 586 // we don't care if it fails, this is best-effort. 587 future.cancel(((Cancellation) localValue).wasInterrupted); 588 } 589 return false; 590 } 591 592 /** 593 * Returns a value that satisfies the contract of the {@link #value} field based on the state of 594 * given future. 595 * 596 * <p>This is approximately the inverse of {@link #getDoneValue(Object)} 597 */ 598 private static Object getFutureValue(ListenableFuture<?> future) { 599 if (future instanceof Trusted) { 600 // Break encapsulation for Trusted instances since we know that subclasses cannot override 601 // .get() and therefore this is equivalent to calling .get() and unpacking the exceptions like 602 // we do below (just much faster because it is a single field read instead of a read, several 603 // branches and possibly creating exceptions). 604 Object v = ((AbstractFuture<?>) future).value(); 605 if (v instanceof Cancellation) { 606 // If the other future was interrupted, clear the interrupted bit while preserving the cause 607 // this will make it consistent with how non-trustedfutures work which cannot propagate the 608 // wasInterrupted bit 609 Cancellation c = (Cancellation) v; 610 if (c.wasInterrupted) { 611 v = 612 c.cause != null 613 ? new Cancellation(/* wasInterrupted= */ false, c.cause) 614 : Cancellation.CAUSELESS_CANCELLED; 615 } 616 } 617 // requireNonNull is safe as long as we call this method only on completed futures. 618 return requireNonNull(v); 619 } 620 if (future instanceof InternalFutureFailureAccess) { 621 Throwable throwable = 622 InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future); 623 if (throwable != null) { 624 return new Failure(throwable); 625 } 626 } 627 boolean wasCancelled = future.isCancelled(); 628 // Don't allocate a CancellationException if it's not necessary 629 if (!GENERATE_CANCELLATION_CAUSES & wasCancelled) { 630 /* 631 * requireNonNull is safe because we've initialized CAUSELESS_CANCELLED if 632 * !GENERATE_CANCELLATION_CAUSES. 633 */ 634 return requireNonNull(Cancellation.CAUSELESS_CANCELLED); 635 } 636 // Otherwise calculate the value by calling .get() 637 try { 638 Object v = getUninterruptibly(future); 639 if (wasCancelled) { 640 return new Cancellation( 641 false, 642 new IllegalArgumentException( 643 "get() did not throw CancellationException, despite reporting " 644 + "isCancelled() == true: " 645 + future)); 646 } 647 return v == null ? NULL : v; 648 } catch (ExecutionException exception) { 649 if (wasCancelled) { 650 return new Cancellation( 651 false, 652 new IllegalArgumentException( 653 "get() did not throw CancellationException, despite reporting " 654 + "isCancelled() == true: " 655 + future, 656 exception)); 657 } 658 return new Failure(exception.getCause()); 659 } catch (CancellationException cancellation) { 660 if (!wasCancelled) { 661 return new Failure( 662 new IllegalArgumentException( 663 "get() threw CancellationException, despite reporting isCancelled() == false: " 664 + future, 665 cancellation)); 666 } 667 return new Cancellation(false, cancellation); 668 } catch (Exception | Error t) { // sneaky checked exception 669 return new Failure(t); 670 } 671 } 672 673 /** 674 * An inlined private copy of {@link Uninterruptibles#getUninterruptibly} used to break an 675 * internal dependency on other /util/concurrent classes. 676 */ 677 @ParametricNullness 678 private static <V extends @Nullable Object> V getUninterruptibly(Future<V> future) 679 throws ExecutionException { 680 boolean interrupted = false; 681 try { 682 while (true) { 683 try { 684 return future.get(); 685 } catch (InterruptedException e) { 686 interrupted = true; 687 } 688 } 689 } finally { 690 if (interrupted) { 691 interruptCurrentThread(); 692 } 693 } 694 } 695 696 /** Unblocks all threads and runs all listeners. */ 697 private static void complete(AbstractFuture<?> param, boolean callInterruptTask) { 698 // Declare a "true" local variable so that the Checker Framework will infer nullness. 699 AbstractFuture<?> future = param; 700 701 Listener next = null; 702 outer: 703 while (true) { 704 future.releaseWaiters(); 705 /* 706 * We call interruptTask() immediately before afterDone() so that migrating between the two 707 * can be a no-op. 708 */ 709 if (callInterruptTask) { 710 future.interruptTask(); 711 /* 712 * Interruption doesn't propagate through a DelegatingToFuture chain (see getFutureValue), 713 * so don't invoke interruptTask on any subsequent futures. 714 */ 715 callInterruptTask = false; 716 } 717 // We call this before the listeners in order to avoid needing to manage a separate stack data 718 // structure for them. Also, some implementations rely on this running prior to listeners 719 // so that the cleanup work is visible to listeners. 720 // afterDone() should be generally fast and only used for cleanup work... but in theory can 721 // also be recursive and create StackOverflowErrors 722 future.afterDone(); 723 // push the current set of listeners onto next 724 next = future.clearListeners(next); 725 future = null; 726 while (next != null) { 727 Listener curr = next; 728 next = next.next; 729 /* 730 * requireNonNull is safe because the listener stack never contains TOMBSTONE until after 731 * clearListeners. 732 */ 733 Runnable task = requireNonNull(curr.task); 734 if (task instanceof DelegatingToFuture) { 735 DelegatingToFuture<?> setFuture = (DelegatingToFuture<?>) task; 736 // We unwind setFuture specifically to avoid StackOverflowErrors in the case of long 737 // chains of DelegatingToFutures 738 // Handling this special case is important because there is no way to pass an executor to 739 // setFuture, so a user couldn't break the chain by doing this themselves. It is also 740 // potentially common if someone writes a recursive Futures.transformAsync transformer. 741 future = setFuture.owner; 742 if (future.value() == setFuture) { 743 Object valueToSet = getFutureValue(setFuture.future); 744 if (casValue(future, setFuture, valueToSet)) { 745 continue outer; 746 } 747 } 748 // otherwise the future we were trying to set is already done. 749 } else { 750 /* 751 * requireNonNull is safe because the listener stack never contains TOMBSTONE until after 752 * clearListeners. 753 */ 754 executeListener(task, requireNonNull(curr.executor)); 755 } 756 } 757 break; 758 } 759 } 760 761 /** 762 * Callback method that is called exactly once after the future is completed. 763 * 764 * <p>If {@link #interruptTask} is also run during completion, {@link #afterDone} runs after it. 765 * 766 * <p>The default implementation of this method in {@code AbstractFuture} does nothing. This is 767 * intended for very lightweight cleanup work, for example, timing statistics or clearing fields. 768 * If your task does anything heavier consider, just using a listener with an executor. 769 * 770 * @since 20.0 771 */ 772 @ForOverride 773 protected void afterDone() {} 774 775 // TODO(b/114236866): Inherit doc from InternalFutureFailureAccess. Also, -link to its URL. 776 /** 777 * Usually returns {@code null} but, if this {@code Future} has failed, may <i>optionally</i> 778 * return the cause of the failure. "Failure" means specifically "completed with an exception"; it 779 * does not include "was cancelled." To be explicit: If this method returns a non-null value, 780 * then: 781 * 782 * <ul> 783 * <li>{@code isDone()} must return {@code true} 784 * <li>{@code isCancelled()} must return {@code false} 785 * <li>{@code get()} must not block, and it must throw an {@code ExecutionException} with the 786 * return value of this method as its cause 787 * </ul> 788 * 789 * <p>This method is {@code protected} so that classes like {@code 790 * com.google.common.util.concurrent.SettableFuture} do not expose it to their users as an 791 * instance method. In the unlikely event that you need to call this method, call {@link 792 * InternalFutures#tryInternalFastPathGetFailure(InternalFutureFailureAccess)}. 793 * 794 * @since 27.0 795 */ 796 @Override 797 /* 798 * We should annotate the superclass, InternalFutureFailureAccess, to say that its copy of this 799 * method returns @Nullable, too. However, we're not sure if we want to make any changes to that 800 * class, since it's in a separate artifact that we planned to release only a single version of. 801 */ 802 protected final @Nullable Throwable tryInternalFastPathGetFailure() { 803 if (this instanceof Trusted) { 804 @RetainedLocalRef Object localValue = value(); 805 if (localValue instanceof Failure) { 806 return ((Failure) localValue).exception; 807 } 808 } 809 return null; 810 } 811 812 /** 813 * If this future has been cancelled (and possibly interrupted), cancels (and possibly interrupts) 814 * the given future (if available). 815 */ 816 @SuppressWarnings("nullness") // TODO(b/147136275): Remove once our checker understands & and |. 817 final void maybePropagateCancellationTo(@Nullable Future<?> related) { 818 if (related != null & isCancelled()) { 819 related.cancel(wasInterrupted()); 820 } 821 } 822 823 /** 824 * Clears the {@link #listeners} list and prepends its contents to {@code onto}, least recently 825 * added first. 826 */ 827 private @Nullable Listener clearListeners(@Nullable Listener onto) { 828 // We need to 829 // 1. atomically swap the listeners with TOMBSTONE, this is because addListener uses that 830 // to synchronize with us 831 // 2. reverse the linked list, because despite our rather clear contract, people depend on us 832 // executing listeners in the order they were added 833 // 3. push all the items onto 'onto' and return the new head of the stack 834 Listener head = gasListeners(Listener.TOMBSTONE); 835 Listener reversedList = onto; 836 while (head != null) { 837 Listener tmp = head; 838 head = head.next; 839 tmp.next = reversedList; 840 reversedList = tmp; 841 } 842 return reversedList; 843 } 844 845 // TODO(user): move parts into a default method on ListenableFuture? 846 @Override 847 public String toString() { 848 // TODO(cpovirk): Presize to something plausible? 849 StringBuilder builder = new StringBuilder(); 850 if (getClass().getName().startsWith("com.google.common.util.concurrent.")) { 851 builder.append(getClass().getSimpleName()); 852 } else { 853 builder.append(getClass().getName()); 854 } 855 builder.append('@').append(toHexString(identityHashCode(this))).append("[status="); 856 if (isCancelled()) { 857 builder.append("CANCELLED"); 858 } else if (isDone()) { 859 addDoneString(builder); 860 } else { 861 addPendingString(builder); // delegates to addDoneString if future completes midway 862 } 863 return builder.append("]").toString(); 864 } 865 866 /** 867 * Provide a human-readable explanation of why this future has not yet completed. 868 * 869 * @return null if an explanation cannot be provided (e.g. because the future is done). 870 * @since 23.0 871 */ 872 protected @Nullable String pendingToString() { 873 // TODO(diamondm) consider moving this into addPendingString so it's always in the output 874 if (this instanceof ScheduledFuture) { 875 return "remaining delay=[" + ((ScheduledFuture) this).getDelay(MILLISECONDS) + " ms]"; 876 } 877 return null; 878 } 879 880 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 881 private void addPendingString(StringBuilder builder) { 882 // Capture current builder length so it can be truncated if this future ends up completing while 883 // the toString is being calculated 884 int truncateLength = builder.length(); 885 886 builder.append("PENDING"); 887 888 @RetainedLocalRef Object localValue = value(); 889 if (localValue instanceof DelegatingToFuture) { 890 builder.append(", setFuture=["); 891 appendUserObject(builder, ((DelegatingToFuture) localValue).future); 892 builder.append("]"); 893 } else { 894 String pendingDescription; 895 try { 896 pendingDescription = Strings.emptyToNull(pendingToString()); 897 } catch (Throwable e) { 898 /* 899 * We want to catch (Exception | StackOverflowError), but we can't under environments where 900 * StackOverflowError doesn't exist. 901 */ 902 rethrowIfErrorOtherThanStackOverflow(e); 903 // The Throwable is either a RuntimeException, an Error, or sneaky checked exception. 904 // 905 // Don't call getMessage or toString() on the exception, in case the exception thrown by the 906 // subclass is implemented with bugs similar to the subclass. 907 pendingDescription = "Exception thrown from implementation: " + e.getClass(); 908 } 909 if (pendingDescription != null) { 910 builder.append(", info=[").append(pendingDescription).append("]"); 911 } 912 } 913 914 // The future may complete while calculating the toString, so we check once more to see if the 915 // future is done 916 if (isDone()) { 917 // Truncate anything that was appended before realizing this future is done 918 builder.delete(truncateLength, builder.length()); 919 addDoneString(builder); 920 } 921 } 922 923 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 924 private void addDoneString(StringBuilder builder) { 925 try { 926 V value = getUninterruptibly(this); 927 builder.append("SUCCESS, result=["); 928 appendResultObject(builder, value); 929 builder.append("]"); 930 } catch (ExecutionException e) { 931 builder.append("FAILURE, cause=[").append(e.getCause()).append("]"); 932 } catch (CancellationException e) { 933 builder.append("CANCELLED"); // shouldn't be reachable 934 } catch (Exception e) { // sneaky checked exception 935 builder.append("UNKNOWN, cause=[").append(e.getClass()).append(" thrown from get()]"); 936 } 937 } 938 939 /** 940 * Any object can be the result of a Future, and not every object has a reasonable toString() 941 * implementation. Using a reconstruction of the default Object.toString() prevents OOMs and stack 942 * overflows, and helps avoid sensitive data inadvertently ending up in exception messages. 943 */ 944 private void appendResultObject(StringBuilder builder, @Nullable Object o) { 945 if (o == null) { 946 builder.append("null"); 947 } else if (o == this) { 948 builder.append("this future"); 949 } else { 950 builder 951 .append(o.getClass().getName()) 952 .append("@") 953 .append(Integer.toHexString(System.identityHashCode(o))); 954 } 955 } 956 957 /** Helper for printing user supplied objects into our toString method. */ 958 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 959 private void appendUserObject(StringBuilder builder, @Nullable Object o) { 960 // This is some basic recursion detection for when people create cycles via set/setFuture or 961 // when deep chains of futures exist resulting in a StackOverflowError. We could detect 962 // arbitrary cycles using a thread local but this should be a good enough solution (it is also 963 // what jdk collections do in these cases) 964 try { 965 if (o == this) { 966 builder.append("this future"); 967 } else { 968 builder.append(o); 969 } 970 } catch (Throwable e) { 971 /* 972 * We want to catch (Exception | StackOverflowError), but we can't under environments where 973 * StackOverflowError doesn't exist. 974 */ 975 rethrowIfErrorOtherThanStackOverflow(e); 976 // The Throwable is either a RuntimeException, an Error, or sneaky checked exception. 977 // 978 // Don't call getMessage or toString() on the exception, in case the exception thrown by the 979 // user object is implemented with bugs similar to the user object. 980 builder.append("Exception thrown from implementation: ").append(e.getClass()); 981 } 982 } 983 984 /** 985 * Submits the given runnable to the given {@link Executor} catching and logging all {@linkplain 986 * RuntimeException runtime exceptions} thrown by the executor. 987 */ 988 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 989 private static void executeListener(Runnable runnable, Executor executor) { 990 try { 991 executor.execute(runnable); 992 } catch (Exception e) { // sneaky checked exception 993 // Log it and keep going -- bad runnable and/or executor. Don't punish the other runnables if 994 // we're given a bad one. We only catch Exception because we want Errors to propagate up. 995 log.get() 996 .log( 997 SEVERE, 998 "RuntimeException while executing runnable " 999 + runnable 1000 + " with executor " 1001 + executor, 1002 e); 1003 } 1004 } 1005 1006 private static CancellationException cancellationExceptionWithCause( 1007 String message, @Nullable Throwable cause) { 1008 CancellationException exception = new CancellationException(message); 1009 exception.initCause(cause); 1010 return exception; 1011 } 1012}