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 java.lang.Integer.toHexString; 020import static java.lang.System.identityHashCode; 021import static java.util.Objects.requireNonNull; 022import static java.util.concurrent.TimeUnit.MILLISECONDS; 023import static java.util.concurrent.TimeUnit.NANOSECONDS; 024import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater; 025 026import com.google.common.annotations.GwtCompatible; 027import com.google.common.base.Strings; 028import com.google.common.util.concurrent.internal.InternalFutureFailureAccess; 029import com.google.common.util.concurrent.internal.InternalFutures; 030import com.google.errorprone.annotations.CanIgnoreReturnValue; 031import com.google.errorprone.annotations.ForOverride; 032import com.google.j2objc.annotations.ReflectionSupport; 033import com.google.j2objc.annotations.RetainedLocalRef; 034import java.lang.reflect.Field; 035import java.security.AccessController; 036import java.security.PrivilegedActionException; 037import java.security.PrivilegedExceptionAction; 038import java.util.Locale; 039import java.util.concurrent.CancellationException; 040import java.util.concurrent.ExecutionException; 041import java.util.concurrent.Executor; 042import java.util.concurrent.Future; 043import java.util.concurrent.ScheduledFuture; 044import java.util.concurrent.TimeUnit; 045import java.util.concurrent.TimeoutException; 046import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; 047import java.util.concurrent.locks.LockSupport; 048import java.util.logging.Level; 049import javax.annotation.CheckForNull; 050import org.checkerframework.checker.nullness.qual.Nullable; 051import sun.misc.Unsafe; 052 053/** 054 * An abstract implementation of {@link ListenableFuture}, intended for advanced users only. More 055 * common ways to create a {@code ListenableFuture} include instantiating a {@link SettableFuture}, 056 * submitting a task to a {@link ListeningExecutorService}, and deriving a {@code Future} from an 057 * existing one, typically using methods like {@link Futures#transform(ListenableFuture, 058 * com.google.common.base.Function, java.util.concurrent.Executor) Futures.transform} and {@link 059 * Futures#catching(ListenableFuture, Class, com.google.common.base.Function, 060 * java.util.concurrent.Executor) Futures.catching}. 061 * 062 * <p>This class implements all methods in {@code ListenableFuture}. Subclasses should provide a way 063 * to set the result of the computation through the protected methods {@link #set(Object)}, {@link 064 * #setFuture(ListenableFuture)} and {@link #setException(Throwable)}. Subclasses may also override 065 * {@link #afterDone()}, which will be invoked automatically when the future completes. Subclasses 066 * should rarely override other methods. 067 * 068 * @author Sven Mawson 069 * @author Luke Sandberg 070 * @since 1.0 071 */ 072@SuppressWarnings({ 073 // Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, || 074 "ShortCircuitBoolean", 075 "nullness", // TODO(b/147136275): Remove once our checker understands & and |. 076}) 077@GwtCompatible(emulated = true) 078@ReflectionSupport(value = ReflectionSupport.Level.FULL) 079@ElementTypesAreNonnullByDefault 080public abstract class AbstractFuture<V extends @Nullable Object> extends InternalFutureFailureAccess 081 implements ListenableFuture<V> { 082 static final boolean GENERATE_CANCELLATION_CAUSES; 083 084 static { 085 // System.getProperty may throw if the security policy does not permit access. 086 boolean generateCancellationCauses; 087 try { 088 generateCancellationCauses = 089 Boolean.parseBoolean( 090 System.getProperty("guava.concurrent.generate_cancellation_cause", "false")); 091 } catch (SecurityException e) { 092 generateCancellationCauses = false; 093 } 094 GENERATE_CANCELLATION_CAUSES = generateCancellationCauses; 095 } 096 097 /** 098 * Tag interface marking trusted subclasses. This enables some optimizations. The implementation 099 * of this interface must also be an AbstractFuture and must not override or expose for overriding 100 * any of the public methods of ListenableFuture. 101 */ 102 interface Trusted<V extends @Nullable Object> extends ListenableFuture<V> {} 103 104 /** 105 * A less abstract subclass of AbstractFuture. This can be used to optimize setFuture by ensuring 106 * that {@link #get} calls exactly the implementation of {@link AbstractFuture#get}. 107 */ 108 abstract static class TrustedFuture<V extends @Nullable Object> extends AbstractFuture<V> 109 implements Trusted<V> { 110 @CanIgnoreReturnValue 111 @Override 112 @ParametricNullness 113 public final V get() throws InterruptedException, ExecutionException { 114 return super.get(); 115 } 116 117 @CanIgnoreReturnValue 118 @Override 119 @ParametricNullness 120 public final V get(long timeout, TimeUnit unit) 121 throws InterruptedException, ExecutionException, TimeoutException { 122 return super.get(timeout, unit); 123 } 124 125 @Override 126 public final boolean isDone() { 127 return super.isDone(); 128 } 129 130 @Override 131 public final boolean isCancelled() { 132 return super.isCancelled(); 133 } 134 135 @Override 136 public final void addListener(Runnable listener, Executor executor) { 137 super.addListener(listener, executor); 138 } 139 140 @CanIgnoreReturnValue 141 @Override 142 public final boolean cancel(boolean mayInterruptIfRunning) { 143 return super.cancel(mayInterruptIfRunning); 144 } 145 } 146 147 static final LazyLogger log = new LazyLogger(AbstractFuture.class); 148 149 // A heuristic for timed gets. If the remaining timeout is less than this, spin instead of 150 // blocking. This value is what AbstractQueuedSynchronizer uses. 151 private static final long SPIN_THRESHOLD_NANOS = 1000L; 152 153 private static final AtomicHelper ATOMIC_HELPER; 154 155 static { 156 AtomicHelper helper; 157 Throwable thrownUnsafeFailure = null; 158 Throwable thrownAtomicReferenceFieldUpdaterFailure = null; 159 160 try { 161 helper = new UnsafeAtomicHelper(); 162 } catch (Exception | Error unsafeFailure) { // sneaky checked exception 163 thrownUnsafeFailure = unsafeFailure; 164 // catch absolutely everything and fall through to our 165 // 'AtomicReferenceFieldUpdaterAtomicHelper' The access control checks that ARFU does means 166 // the caller class has to be AbstractFuture instead of 167 // AtomicReferenceFieldUpdaterAtomicHelper, so we annoyingly define these here 168 try { 169 helper = 170 new AtomicReferenceFieldUpdaterAtomicHelper( 171 newUpdater(Waiter.class, Thread.class, "thread"), 172 newUpdater(Waiter.class, Waiter.class, "next"), 173 newUpdater(AbstractFuture.class, Waiter.class, "waiters"), 174 newUpdater(AbstractFuture.class, Listener.class, "listeners"), 175 newUpdater(AbstractFuture.class, Object.class, "value")); 176 } catch (Exception // sneaky checked exception 177 | Error atomicReferenceFieldUpdaterFailure) { 178 // Some Android 5.0.x Samsung devices have bugs in JDK reflection APIs that cause 179 // getDeclaredField to throw a NoSuchFieldException when the field is definitely there. 180 // For these users fallback to a suboptimal implementation, based on synchronized. This will 181 // be a definite performance hit to those users. 182 thrownAtomicReferenceFieldUpdaterFailure = atomicReferenceFieldUpdaterFailure; 183 helper = new SynchronizedHelper(); 184 } 185 } 186 ATOMIC_HELPER = helper; 187 188 // Prevent rare disastrous classloading in first call to LockSupport.park. 189 // See: https://bugs.openjdk.java.net/browse/JDK-8074773 190 @SuppressWarnings("unused") 191 Class<?> ensureLoaded = LockSupport.class; 192 193 // Log after all static init is finished; if an installed logger uses any Futures methods, it 194 // shouldn't break in cases where reflection is missing/broken. 195 if (thrownAtomicReferenceFieldUpdaterFailure != null) { 196 log.get().log(Level.SEVERE, "UnsafeAtomicHelper is broken!", thrownUnsafeFailure); 197 log.get() 198 .log( 199 Level.SEVERE, 200 "AtomicReferenceFieldUpdaterAtomicHelper is broken!", 201 thrownAtomicReferenceFieldUpdaterFailure); 202 } 203 } 204 205 /** Waiter links form a Treiber stack, in the {@link #waiters} field. */ 206 private static final class Waiter { 207 static final Waiter TOMBSTONE = new Waiter(false /* ignored param */); 208 209 @CheckForNull volatile Thread thread; 210 @CheckForNull volatile Waiter next; 211 212 /** 213 * Constructor for the TOMBSTONE, avoids use of ATOMIC_HELPER in case this class is loaded 214 * before the ATOMIC_HELPER. Apparently this is possible on some android platforms. 215 */ 216 Waiter(boolean unused) {} 217 218 Waiter() { 219 // avoid volatile write, write is made visible by subsequent CAS on waiters field 220 ATOMIC_HELPER.putThread(this, Thread.currentThread()); 221 } 222 223 // non-volatile write to the next field. Should be made visible by subsequent CAS on waiters 224 // field. 225 void setNext(@CheckForNull Waiter next) { 226 ATOMIC_HELPER.putNext(this, next); 227 } 228 229 void unpark() { 230 // This is racy with removeWaiter. The consequence of the race is that we may spuriously call 231 // unpark even though the thread has already removed itself from the list. But even if we did 232 // use a CAS, that race would still exist (it would just be ever so slightly smaller). 233 Thread w = thread; 234 if (w != null) { 235 thread = null; 236 LockSupport.unpark(w); 237 } 238 } 239 } 240 241 /** 242 * Marks the given node as 'deleted' (null waiter) and then scans the list to unlink all deleted 243 * nodes. This is an O(n) operation in the common case (and O(n^2) in the worst), but we are saved 244 * by two things. 245 * 246 * <ul> 247 * <li>This is only called when a waiting thread times out or is interrupted. Both of which 248 * should be rare. 249 * <li>The waiters list should be very short. 250 * </ul> 251 */ 252 private void removeWaiter(Waiter node) { 253 node.thread = null; // mark as 'deleted' 254 restart: 255 while (true) { 256 Waiter pred = null; 257 Waiter curr = waiters; 258 if (curr == Waiter.TOMBSTONE) { 259 return; // give up if someone is calling complete 260 } 261 Waiter succ; 262 while (curr != null) { 263 succ = curr.next; 264 if (curr.thread != null) { // we aren't unlinking this node, update pred. 265 pred = curr; 266 } else if (pred != null) { // We are unlinking this node and it has a predecessor. 267 pred.next = succ; 268 if (pred.thread == null) { // We raced with another node that unlinked pred. Restart. 269 continue restart; 270 } 271 } else if (!ATOMIC_HELPER.casWaiters(this, curr, succ)) { // We are unlinking head 272 continue restart; // We raced with an add or complete 273 } 274 curr = succ; 275 } 276 break; 277 } 278 } 279 280 /** Listeners also form a stack through the {@link #listeners} field. */ 281 private static final class Listener { 282 static final Listener TOMBSTONE = new Listener(); 283 @CheckForNull // null only for TOMBSTONE 284 final Runnable task; 285 @CheckForNull // null only for TOMBSTONE 286 final Executor executor; 287 288 // writes to next are made visible by subsequent CAS's on the listeners field 289 @CheckForNull Listener next; 290 291 Listener(Runnable task, Executor executor) { 292 this.task = task; 293 this.executor = executor; 294 } 295 296 Listener() { 297 this.task = null; 298 this.executor = null; 299 } 300 } 301 302 /** A special value to represent {@code null}. */ 303 private static final Object NULL = new Object(); 304 305 /** A special value to represent failure, when {@link #setException} is called successfully. */ 306 private static final class Failure { 307 static final Failure FALLBACK_INSTANCE = 308 new Failure( 309 new Throwable("Failure occurred while trying to finish a future.") { 310 @Override 311 public synchronized Throwable fillInStackTrace() { 312 return this; // no stack trace 313 } 314 }); 315 final Throwable exception; 316 317 Failure(Throwable exception) { 318 this.exception = checkNotNull(exception); 319 } 320 } 321 322 /** A special value to represent cancellation and the 'wasInterrupted' bit. */ 323 private static final class Cancellation { 324 // constants to use when GENERATE_CANCELLATION_CAUSES = false 325 @CheckForNull static final Cancellation CAUSELESS_INTERRUPTED; 326 @CheckForNull static final Cancellation CAUSELESS_CANCELLED; 327 328 static { 329 if (GENERATE_CANCELLATION_CAUSES) { 330 CAUSELESS_CANCELLED = null; 331 CAUSELESS_INTERRUPTED = null; 332 } else { 333 CAUSELESS_CANCELLED = new Cancellation(false, null); 334 CAUSELESS_INTERRUPTED = new Cancellation(true, null); 335 } 336 } 337 338 final boolean wasInterrupted; 339 @CheckForNull final Throwable cause; 340 341 Cancellation(boolean wasInterrupted, @CheckForNull Throwable cause) { 342 this.wasInterrupted = wasInterrupted; 343 this.cause = cause; 344 } 345 } 346 347 /** A special value that encodes the 'setFuture' state. */ 348 private static final class SetFuture<V extends @Nullable Object> implements Runnable { 349 final AbstractFuture<V> owner; 350 final ListenableFuture<? extends V> future; 351 352 SetFuture(AbstractFuture<V> owner, ListenableFuture<? extends V> future) { 353 this.owner = owner; 354 this.future = future; 355 } 356 357 @Override 358 public void run() { 359 if (owner.value != this) { 360 // nothing to do, we must have been cancelled, don't bother inspecting the future. 361 return; 362 } 363 Object valueToSet = getFutureValue(future); 364 if (ATOMIC_HELPER.casValue(owner, this, valueToSet)) { 365 complete( 366 owner, 367 /* 368 * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so 369 * don't invoke interruptTask. 370 */ 371 false); 372 } 373 } 374 } 375 376 // TODO(lukes): investigate using the @Contended annotation on these fields when jdk8 is 377 // available. 378 /** 379 * This field encodes the current state of the future. 380 * 381 * <p>The valid values are: 382 * 383 * <ul> 384 * <li>{@code null} initial state, nothing has happened. 385 * <li>{@link Cancellation} terminal state, {@code cancel} was called. 386 * <li>{@link Failure} terminal state, {@code setException} was called. 387 * <li>{@link SetFuture} intermediate state, {@code setFuture} was called. 388 * <li>{@link #NULL} terminal state, {@code set(null)} was called. 389 * <li>Any other non-null value, terminal state, {@code set} was called with a non-null 390 * argument. 391 * </ul> 392 */ 393 @CheckForNull private volatile Object value; 394 395 /** All listeners. */ 396 @CheckForNull private volatile Listener listeners; 397 398 /** All waiting threads. */ 399 @CheckForNull private volatile Waiter waiters; 400 401 /** Constructor for use by subclasses. */ 402 protected AbstractFuture() {} 403 404 // Gets and Timed Gets 405 // 406 // * Be responsive to interruption 407 // * Don't create Waiter nodes if you aren't going to park, this helps reduce contention on the 408 // waiters field. 409 // * Future completion is defined by when #value becomes non-null/non SetFuture 410 // * Future completion can be observed if the waiters field contains a TOMBSTONE 411 412 // Timed Get 413 // There are a few design constraints to consider 414 // * We want to be responsive to small timeouts, unpark() has non trivial latency overheads (I 415 // have observed 12 micros on 64-bit linux systems to wake up a parked thread). So if the 416 // timeout is small we shouldn't park(). This needs to be traded off with the cpu overhead of 417 // spinning, so we use SPIN_THRESHOLD_NANOS which is what AbstractQueuedSynchronizer uses for 418 // similar purposes. 419 // * We want to behave reasonably for timeouts of 0 420 // * We are more responsive to completion than timeouts. This is because parkNanos depends on 421 // system scheduling and as such we could either miss our deadline, or unpark() could be delayed 422 // so that it looks like we timed out even though we didn't. For comparison FutureTask respects 423 // completion preferably and AQS is non-deterministic (depends on where in the queue the waiter 424 // is). If we wanted to be strict about it, we could store the unpark() time in the Waiter node 425 // and we could use that to make a decision about whether or not we timed out prior to being 426 // unparked. 427 428 /** 429 * {@inheritDoc} 430 * 431 * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the 432 * current thread is interrupted during the call, even if the value is already available. 433 * 434 * @throws CancellationException {@inheritDoc} 435 */ 436 @SuppressWarnings("LabelledBreakTarget") // TODO(b/345814817): Maybe fix? 437 @CanIgnoreReturnValue 438 @Override 439 @ParametricNullness 440 public V get(long timeout, TimeUnit unit) 441 throws InterruptedException, TimeoutException, ExecutionException { 442 // NOTE: if timeout < 0, remainingNanos will be < 0 and we will fall into the while(true) loop 443 // at the bottom and throw a timeoutexception. 444 final long timeoutNanos = unit.toNanos(timeout); // we rely on the implicit null check on unit. 445 long remainingNanos = timeoutNanos; 446 if (Thread.interrupted()) { 447 throw new InterruptedException(); 448 } 449 @RetainedLocalRef Object localValue = value; 450 if (localValue != null & !(localValue instanceof SetFuture)) { 451 return getDoneValue(localValue); 452 } 453 // we delay calling nanoTime until we know we will need to either park or spin 454 final long endNanos = remainingNanos > 0 ? System.nanoTime() + remainingNanos : 0; 455 long_wait_loop: 456 if (remainingNanos >= SPIN_THRESHOLD_NANOS) { 457 Waiter oldHead = waiters; 458 if (oldHead != Waiter.TOMBSTONE) { 459 Waiter node = new Waiter(); 460 do { 461 node.setNext(oldHead); 462 if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) { 463 while (true) { 464 OverflowAvoidingLockSupport.parkNanos(this, remainingNanos); 465 // Check interruption first, if we woke up due to interruption we need to honor that. 466 if (Thread.interrupted()) { 467 removeWaiter(node); 468 throw new InterruptedException(); 469 } 470 471 // Otherwise re-read and check doneness. If we loop then it must have been a spurious 472 // wakeup 473 localValue = value; 474 if (localValue != null & !(localValue instanceof SetFuture)) { 475 return getDoneValue(localValue); 476 } 477 478 // timed out? 479 remainingNanos = endNanos - System.nanoTime(); 480 if (remainingNanos < SPIN_THRESHOLD_NANOS) { 481 // Remove the waiter, one way or another we are done parking this thread. 482 removeWaiter(node); 483 break long_wait_loop; // jump down to the busy wait loop 484 } 485 } 486 } 487 oldHead = waiters; // re-read and loop. 488 } while (oldHead != Waiter.TOMBSTONE); 489 } 490 // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a 491 // waiter. 492 // requireNonNull is safe because value is always set before TOMBSTONE. 493 return getDoneValue(requireNonNull(value)); 494 } 495 // If we get here then we have remainingNanos < SPIN_THRESHOLD_NANOS and there is no node on the 496 // waiters list 497 while (remainingNanos > 0) { 498 localValue = value; 499 if (localValue != null & !(localValue instanceof SetFuture)) { 500 return getDoneValue(localValue); 501 } 502 if (Thread.interrupted()) { 503 throw new InterruptedException(); 504 } 505 remainingNanos = endNanos - System.nanoTime(); 506 } 507 508 String futureToString = toString(); 509 final String unitString = unit.toString().toLowerCase(Locale.ROOT); 510 String message = "Waited " + timeout + " " + unit.toString().toLowerCase(Locale.ROOT); 511 // Only report scheduling delay if larger than our spin threshold - otherwise it's just noise 512 if (remainingNanos + SPIN_THRESHOLD_NANOS < 0) { 513 // We over-waited for our timeout. 514 message += " (plus "; 515 long overWaitNanos = -remainingNanos; 516 long overWaitUnits = unit.convert(overWaitNanos, NANOSECONDS); 517 long overWaitLeftoverNanos = overWaitNanos - unit.toNanos(overWaitUnits); 518 boolean shouldShowExtraNanos = 519 overWaitUnits == 0 || overWaitLeftoverNanos > SPIN_THRESHOLD_NANOS; 520 if (overWaitUnits > 0) { 521 message += overWaitUnits + " " + unitString; 522 if (shouldShowExtraNanos) { 523 message += ","; 524 } 525 message += " "; 526 } 527 if (shouldShowExtraNanos) { 528 message += overWaitLeftoverNanos + " nanoseconds "; 529 } 530 531 message += "delay)"; 532 } 533 // It's confusing to see a completed future in a timeout message; if isDone() returns false, 534 // then we know it must have given a pending toString value earlier. If not, then the future 535 // completed after the timeout expired, and the message might be success. 536 if (isDone()) { 537 throw new TimeoutException(message + " but future completed as timeout expired"); 538 } 539 throw new TimeoutException(message + " for " + futureToString); 540 } 541 542 /** 543 * {@inheritDoc} 544 * 545 * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the 546 * current thread is interrupted during the call, even if the value is already available. 547 * 548 * @throws CancellationException {@inheritDoc} 549 */ 550 @CanIgnoreReturnValue 551 @Override 552 @ParametricNullness 553 public V get() throws InterruptedException, ExecutionException { 554 if (Thread.interrupted()) { 555 throw new InterruptedException(); 556 } 557 @RetainedLocalRef Object localValue = value; 558 if (localValue != null & !(localValue instanceof SetFuture)) { 559 return getDoneValue(localValue); 560 } 561 Waiter oldHead = waiters; 562 if (oldHead != Waiter.TOMBSTONE) { 563 Waiter node = new Waiter(); 564 do { 565 node.setNext(oldHead); 566 if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) { 567 // we are on the stack, now wait for completion. 568 while (true) { 569 LockSupport.park(this); 570 // Check interruption first, if we woke up due to interruption we need to honor that. 571 if (Thread.interrupted()) { 572 removeWaiter(node); 573 throw new InterruptedException(); 574 } 575 // Otherwise re-read and check doneness. If we loop then it must have been a spurious 576 // wakeup 577 localValue = value; 578 if (localValue != null & !(localValue instanceof SetFuture)) { 579 return getDoneValue(localValue); 580 } 581 } 582 } 583 oldHead = waiters; // re-read and loop. 584 } while (oldHead != Waiter.TOMBSTONE); 585 } 586 // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a 587 // waiter. 588 // requireNonNull is safe because value is always set before TOMBSTONE. 589 return getDoneValue(requireNonNull(value)); 590 } 591 592 /** Unboxes {@code obj}. Assumes that obj is not {@code null} or a {@link SetFuture}. */ 593 @ParametricNullness 594 private V getDoneValue(Object obj) throws ExecutionException { 595 // While this seems like it might be too branch-y, simple benchmarking proves it to be 596 // unmeasurable (comparing done AbstractFutures with immediateFuture) 597 if (obj instanceof Cancellation) { 598 Cancellation cancellation = (Cancellation) obj; 599 Throwable cause = cancellation.cause; 600 throw cancellationExceptionWithCause("Task was cancelled.", cause); 601 } else if (obj instanceof Failure) { 602 Failure failure = (Failure) obj; 603 Throwable exception = failure.exception; 604 throw new ExecutionException(exception); 605 } else if (obj == NULL) { 606 /* 607 * It's safe to return null because we would only have stored it in the first place if it were 608 * a valid value for V. 609 */ 610 return uncheckedNull(); 611 } else { 612 @SuppressWarnings("unchecked") // this is the only other option 613 V asV = (V) obj; 614 return asV; 615 } 616 } 617 618 @Override 619 public boolean isDone() { 620 @RetainedLocalRef Object localValue = value; 621 return localValue != null & !(localValue instanceof SetFuture); 622 } 623 624 @Override 625 public boolean isCancelled() { 626 @RetainedLocalRef Object localValue = value; 627 return localValue instanceof Cancellation; 628 } 629 630 /** 631 * {@inheritDoc} 632 * 633 * <p>If a cancellation attempt succeeds on a {@code Future} that had previously been {@linkplain 634 * #setFuture set asynchronously}, then the cancellation will also be propagated to the delegate 635 * {@code Future} that was supplied in the {@code setFuture} call. 636 * 637 * <p>Rather than override this method to perform additional cancellation work or cleanup, 638 * subclasses should override {@link #afterDone}, consulting {@link #isCancelled} and {@link 639 * #wasInterrupted} as necessary. This ensures that the work is done even if the future is 640 * cancelled without a call to {@code cancel}, such as by calling {@code 641 * setFuture(cancelledFuture)}. 642 * 643 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 644 * acquire other locks, risking deadlocks. 645 */ 646 @CanIgnoreReturnValue 647 @Override 648 public boolean cancel(boolean mayInterruptIfRunning) { 649 @RetainedLocalRef Object localValue = value; 650 boolean rValue = false; 651 if (localValue == null | localValue instanceof SetFuture) { 652 // Try to delay allocating the exception. At this point we may still lose the CAS, but it is 653 // certainly less likely. 654 Object valueToSet = 655 GENERATE_CANCELLATION_CAUSES 656 ? new Cancellation( 657 mayInterruptIfRunning, new CancellationException("Future.cancel() was called.")) 658 /* 659 * requireNonNull is safe because we've initialized these if 660 * !GENERATE_CANCELLATION_CAUSES. 661 * 662 * TODO(cpovirk): Maybe it would be cleaner to define a CancellationSupplier interface 663 * with two implementations, one that contains causeless Cancellation instances and 664 * the other of which creates new Cancellation instances each time it's called? Yet 665 * another alternative is to fill in a non-null value for each of the fields no matter 666 * what and to just not use it if !GENERATE_CANCELLATION_CAUSES. 667 */ 668 : requireNonNull( 669 mayInterruptIfRunning 670 ? Cancellation.CAUSELESS_INTERRUPTED 671 : Cancellation.CAUSELESS_CANCELLED); 672 AbstractFuture<?> abstractFuture = this; 673 while (true) { 674 if (ATOMIC_HELPER.casValue(abstractFuture, localValue, valueToSet)) { 675 rValue = true; 676 complete(abstractFuture, mayInterruptIfRunning); 677 if (localValue instanceof SetFuture) { 678 // propagate cancellation to the future set in setfuture, this is racy, and we don't 679 // care if we are successful or not. 680 ListenableFuture<?> futureToPropagateTo = ((SetFuture) localValue).future; 681 if (futureToPropagateTo instanceof Trusted) { 682 // If the future is a TrustedFuture then we specifically avoid calling cancel() 683 // this has 2 benefits 684 // 1. for long chains of futures strung together with setFuture we consume less stack 685 // 2. we avoid allocating Cancellation objects at every level of the cancellation 686 // chain 687 // We can only do this for TrustedFuture, because TrustedFuture.cancel is final and 688 // does nothing but delegate to this method. 689 AbstractFuture<?> trusted = (AbstractFuture<?>) futureToPropagateTo; 690 localValue = trusted.value; 691 if (localValue == null | localValue instanceof SetFuture) { 692 abstractFuture = trusted; 693 continue; // loop back up and try to complete the new future 694 } 695 } else { 696 // not a TrustedFuture, call cancel directly. 697 futureToPropagateTo.cancel(mayInterruptIfRunning); 698 } 699 } 700 break; 701 } 702 // obj changed, reread 703 localValue = abstractFuture.value; 704 if (!(localValue instanceof SetFuture)) { 705 // obj cannot be null at this point, because value can only change from null to non-null. 706 // So if value changed (and it did since we lost the CAS), then it cannot be null and 707 // since it isn't a SetFuture, then the future must be done and we should exit the loop 708 break; 709 } 710 } 711 } 712 return rValue; 713 } 714 715 /** 716 * Subclasses can override this method to implement interruption of the future's computation. The 717 * method is invoked automatically by a successful call to {@link #cancel(boolean) cancel(true)}. 718 * 719 * <p>The default implementation does nothing. 720 * 721 * <p>This method is likely to be deprecated. Prefer to override {@link #afterDone}, checking 722 * {@link #wasInterrupted} to decide whether to interrupt your task. 723 * 724 * @since 10.0 725 */ 726 protected void interruptTask() {} 727 728 /** 729 * Returns true if this future was cancelled with {@code mayInterruptIfRunning} set to {@code 730 * true}. 731 * 732 * @since 14.0 733 */ 734 protected final boolean wasInterrupted() { 735 @RetainedLocalRef Object localValue = value; 736 return (localValue instanceof Cancellation) && ((Cancellation) localValue).wasInterrupted; 737 } 738 739 /** 740 * {@inheritDoc} 741 * 742 * @since 10.0 743 */ 744 @Override 745 public void addListener(Runnable listener, Executor executor) { 746 checkNotNull(listener, "Runnable was null."); 747 checkNotNull(executor, "Executor was null."); 748 // Checking isDone and listeners != TOMBSTONE may seem redundant, but our contract for 749 // addListener says that listeners execute 'immediate' if the future isDone(). However, our 750 // protocol for completing a future is to assign the value field (which sets isDone to true) and 751 // then to release waiters, followed by executing afterDone(), followed by releasing listeners. 752 // That means that it is possible to observe that the future isDone and that your listeners 753 // don't execute 'immediately'. By checking isDone here we avoid that. 754 // A corollary to all that is that we don't need to check isDone inside the loop because if we 755 // get into the loop we know that we weren't done when we entered and therefore we aren't under 756 // an obligation to execute 'immediately'. 757 if (!isDone()) { 758 Listener oldHead = listeners; 759 if (oldHead != Listener.TOMBSTONE) { 760 Listener newNode = new Listener(listener, executor); 761 do { 762 newNode.next = oldHead; 763 if (ATOMIC_HELPER.casListeners(this, oldHead, newNode)) { 764 return; 765 } 766 oldHead = listeners; // re-read 767 } while (oldHead != Listener.TOMBSTONE); 768 } 769 } 770 // If we get here then the Listener TOMBSTONE was set, which means the future is done, call 771 // the listener. 772 executeListener(listener, executor); 773 } 774 775 /** 776 * Sets the result of this {@code Future} unless this {@code Future} has already been cancelled or 777 * set (including {@linkplain #setFuture set asynchronously}). When a call to this method returns, 778 * the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> the call was 779 * accepted (in which case it returns {@code true}). If it returns {@code false}, the {@code 780 * Future} may have previously been set asynchronously, in which case its result may not be known 781 * yet. That result, though not yet known, cannot be overridden by a call to a {@code set*} 782 * method, only by a call to {@link #cancel}. 783 * 784 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 785 * acquire other locks, risking deadlocks. 786 * 787 * @param value the value to be used as the result 788 * @return true if the attempt was accepted, completing the {@code Future} 789 */ 790 @CanIgnoreReturnValue 791 protected boolean set(@ParametricNullness V value) { 792 Object valueToSet = value == null ? NULL : value; 793 if (ATOMIC_HELPER.casValue(this, null, valueToSet)) { 794 complete(this, /*callInterruptTask=*/ false); 795 return true; 796 } 797 return false; 798 } 799 800 /** 801 * Sets the failed result of this {@code Future} unless this {@code Future} has already been 802 * cancelled or set (including {@linkplain #setFuture set asynchronously}). When a call to this 803 * method returns, the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> 804 * the call was accepted (in which case it returns {@code true}). If it returns {@code false}, the 805 * {@code Future} may have previously been set asynchronously, in which case its result may not be 806 * known yet. That result, though not yet known, cannot be overridden by a call to a {@code set*} 807 * method, only by a call to {@link #cancel}. 808 * 809 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 810 * acquire other locks, risking deadlocks. 811 * 812 * @param throwable the exception to be used as the failed result 813 * @return true if the attempt was accepted, completing the {@code Future} 814 */ 815 @CanIgnoreReturnValue 816 protected boolean setException(Throwable throwable) { 817 Object valueToSet = new Failure(checkNotNull(throwable)); 818 if (ATOMIC_HELPER.casValue(this, null, valueToSet)) { 819 complete(this, /*callInterruptTask=*/ false); 820 return true; 821 } 822 return false; 823 } 824 825 /** 826 * Sets the result of this {@code Future} to match the supplied input {@code Future} once the 827 * supplied {@code Future} is done, unless this {@code Future} has already been cancelled or set 828 * (including "set asynchronously," defined below). 829 * 830 * <p>If the supplied future is {@linkplain #isDone done} when this method is called and the call 831 * is accepted, then this future is guaranteed to have been completed with the supplied future by 832 * the time this method returns. If the supplied future is not done and the call is accepted, then 833 * the future will be <i>set asynchronously</i>. Note that such a result, though not yet known, 834 * cannot be overridden by a call to a {@code set*} method, only by a call to {@link #cancel}. 835 * 836 * <p>If the call {@code setFuture(delegate)} is accepted and this {@code Future} is later 837 * cancelled, cancellation will be propagated to {@code delegate}. Additionally, any call to 838 * {@code setFuture} after any cancellation will propagate cancellation to the supplied {@code 839 * Future}. 840 * 841 * <p>Note that, even if the supplied future is cancelled and it causes this future to complete, 842 * it will never trigger interruption behavior. In particular, it will not cause this future to 843 * invoke the {@link #interruptTask} method, and the {@link #wasInterrupted} method will not 844 * return {@code true}. 845 * 846 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 847 * acquire other locks, risking deadlocks. 848 * 849 * @param future the future to delegate to 850 * @return true if the attempt was accepted, indicating that the {@code Future} was not previously 851 * cancelled or set. 852 * @since 19.0 853 */ 854 @CanIgnoreReturnValue 855 @SuppressWarnings("Interruption") // We are propagating an interrupt from a caller. 856 protected boolean setFuture(ListenableFuture<? extends V> future) { 857 checkNotNull(future); 858 @RetainedLocalRef Object localValue = value; 859 if (localValue == null) { 860 if (future.isDone()) { 861 Object value = getFutureValue(future); 862 if (ATOMIC_HELPER.casValue(this, null, value)) { 863 complete( 864 this, 865 /* 866 * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so 867 * don't invoke interruptTask. 868 */ 869 false); 870 return true; 871 } 872 return false; 873 } 874 SetFuture<V> valueToSet = new SetFuture<>(this, future); 875 if (ATOMIC_HELPER.casValue(this, null, valueToSet)) { 876 // the listener is responsible for calling completeWithFuture, directExecutor is appropriate 877 // since all we are doing is unpacking a completed future which should be fast. 878 try { 879 future.addListener(valueToSet, DirectExecutor.INSTANCE); 880 } catch (Throwable t) { 881 // Any Exception is either a RuntimeException or sneaky checked exception. 882 // 883 // addListener has thrown an exception! SetFuture.run can't throw any exceptions so this 884 // must have been caused by addListener itself. The most likely explanation is a 885 // misconfigured mock. Try to switch to Failure. 886 Failure failure; 887 try { 888 failure = new Failure(t); 889 } catch (Exception | Error oomMostLikely) { // sneaky checked exception 890 failure = Failure.FALLBACK_INSTANCE; 891 } 892 // Note: The only way this CAS could fail is if cancel() has raced with us. That is ok. 893 boolean unused = ATOMIC_HELPER.casValue(this, valueToSet, failure); 894 } 895 return true; 896 } 897 localValue = value; // we lost the cas, fall through and maybe cancel 898 } 899 // The future has already been set to something. If it is cancellation we should cancel the 900 // incoming future. 901 if (localValue instanceof Cancellation) { 902 // we don't care if it fails, this is best-effort. 903 future.cancel(((Cancellation) localValue).wasInterrupted); 904 } 905 return false; 906 } 907 908 /** 909 * Returns a value that satisfies the contract of the {@link #value} field based on the state of 910 * given future. 911 * 912 * <p>This is approximately the inverse of {@link #getDoneValue(Object)} 913 */ 914 private static Object getFutureValue(ListenableFuture<?> future) { 915 if (future instanceof Trusted) { 916 // Break encapsulation for TrustedFuture instances since we know that subclasses cannot 917 // override .get() (since it is final) and therefore this is equivalent to calling .get() 918 // and unpacking the exceptions like we do below (just much faster because it is a single 919 // field read instead of a read, several branches and possibly creating exceptions). 920 Object v = ((AbstractFuture<?>) future).value; 921 if (v instanceof Cancellation) { 922 // If the other future was interrupted, clear the interrupted bit while preserving the cause 923 // this will make it consistent with how non-trustedfutures work which cannot propagate the 924 // wasInterrupted bit 925 Cancellation c = (Cancellation) v; 926 if (c.wasInterrupted) { 927 v = 928 c.cause != null 929 ? new Cancellation(/* wasInterrupted= */ false, c.cause) 930 : Cancellation.CAUSELESS_CANCELLED; 931 } 932 } 933 // requireNonNull is safe as long as we call this method only on completed futures. 934 return requireNonNull(v); 935 } 936 if (future instanceof InternalFutureFailureAccess) { 937 Throwable throwable = 938 InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future); 939 if (throwable != null) { 940 return new Failure(throwable); 941 } 942 } 943 boolean wasCancelled = future.isCancelled(); 944 // Don't allocate a CancellationException if it's not necessary 945 if (!GENERATE_CANCELLATION_CAUSES & wasCancelled) { 946 /* 947 * requireNonNull is safe because we've initialized CAUSELESS_CANCELLED if 948 * !GENERATE_CANCELLATION_CAUSES. 949 */ 950 return requireNonNull(Cancellation.CAUSELESS_CANCELLED); 951 } 952 // Otherwise calculate the value by calling .get() 953 try { 954 Object v = getUninterruptibly(future); 955 if (wasCancelled) { 956 return new Cancellation( 957 false, 958 new IllegalArgumentException( 959 "get() did not throw CancellationException, despite reporting " 960 + "isCancelled() == true: " 961 + future)); 962 } 963 return v == null ? NULL : v; 964 } catch (ExecutionException exception) { 965 if (wasCancelled) { 966 return new Cancellation( 967 false, 968 new IllegalArgumentException( 969 "get() did not throw CancellationException, despite reporting " 970 + "isCancelled() == true: " 971 + future, 972 exception)); 973 } 974 return new Failure(exception.getCause()); 975 } catch (CancellationException cancellation) { 976 if (!wasCancelled) { 977 return new Failure( 978 new IllegalArgumentException( 979 "get() threw CancellationException, despite reporting isCancelled() == false: " 980 + future, 981 cancellation)); 982 } 983 return new Cancellation(false, cancellation); 984 } catch (Exception | Error t) { // sneaky checked exception 985 return new Failure(t); 986 } 987 } 988 989 /** 990 * An inlined private copy of {@link Uninterruptibles#getUninterruptibly} used to break an 991 * internal dependency on other /util/concurrent classes. 992 */ 993 @ParametricNullness 994 private static <V extends @Nullable Object> V getUninterruptibly(Future<V> future) 995 throws ExecutionException { 996 boolean interrupted = false; 997 try { 998 while (true) { 999 try { 1000 return future.get(); 1001 } catch (InterruptedException e) { 1002 interrupted = true; 1003 } 1004 } 1005 } finally { 1006 if (interrupted) { 1007 Thread.currentThread().interrupt(); 1008 } 1009 } 1010 } 1011 1012 /** Unblocks all threads and runs all listeners. */ 1013 private static void complete(AbstractFuture<?> param, boolean callInterruptTask) { 1014 // Declare a "true" local variable so that the Checker Framework will infer nullness. 1015 AbstractFuture<?> future = param; 1016 1017 Listener next = null; 1018 outer: 1019 while (true) { 1020 future.releaseWaiters(); 1021 /* 1022 * We call interruptTask() immediately before afterDone() so that migrating between the two 1023 * can be a no-op. 1024 */ 1025 if (callInterruptTask) { 1026 future.interruptTask(); 1027 /* 1028 * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so don't 1029 * invoke interruptTask on any subsequent futures. 1030 */ 1031 callInterruptTask = false; 1032 } 1033 // We call this before the listeners in order to avoid needing to manage a separate stack data 1034 // structure for them. Also, some implementations rely on this running prior to listeners 1035 // so that the cleanup work is visible to listeners. 1036 // afterDone() should be generally fast and only used for cleanup work... but in theory can 1037 // also be recursive and create StackOverflowErrors 1038 future.afterDone(); 1039 // push the current set of listeners onto next 1040 next = future.clearListeners(next); 1041 future = null; 1042 while (next != null) { 1043 Listener curr = next; 1044 next = next.next; 1045 /* 1046 * requireNonNull is safe because the listener stack never contains TOMBSTONE until after 1047 * clearListeners. 1048 */ 1049 Runnable task = requireNonNull(curr.task); 1050 if (task instanceof SetFuture) { 1051 SetFuture<?> setFuture = (SetFuture<?>) task; 1052 // We unwind setFuture specifically to avoid StackOverflowErrors in the case of long 1053 // chains of SetFutures 1054 // Handling this special case is important because there is no way to pass an executor to 1055 // setFuture, so a user couldn't break the chain by doing this themselves. It is also 1056 // potentially common if someone writes a recursive Futures.transformAsync transformer. 1057 future = setFuture.owner; 1058 if (future.value == setFuture) { 1059 Object valueToSet = getFutureValue(setFuture.future); 1060 if (ATOMIC_HELPER.casValue(future, setFuture, valueToSet)) { 1061 continue outer; 1062 } 1063 } 1064 // otherwise the future we were trying to set is already done. 1065 } else { 1066 /* 1067 * requireNonNull is safe because the listener stack never contains TOMBSTONE until after 1068 * clearListeners. 1069 */ 1070 executeListener(task, requireNonNull(curr.executor)); 1071 } 1072 } 1073 break; 1074 } 1075 } 1076 1077 /** 1078 * Callback method that is called exactly once after the future is completed. 1079 * 1080 * <p>If {@link #interruptTask} is also run during completion, {@link #afterDone} runs after it. 1081 * 1082 * <p>The default implementation of this method in {@code AbstractFuture} does nothing. This is 1083 * intended for very lightweight cleanup work, for example, timing statistics or clearing fields. 1084 * If your task does anything heavier consider, just using a listener with an executor. 1085 * 1086 * @since 20.0 1087 */ 1088 @ForOverride 1089 protected void afterDone() {} 1090 1091 // TODO(b/114236866): Inherit doc from InternalFutureFailureAccess. Also, -link to its URL. 1092 /** 1093 * Usually returns {@code null} but, if this {@code Future} has failed, may <i>optionally</i> 1094 * return the cause of the failure. "Failure" means specifically "completed with an exception"; it 1095 * does not include "was cancelled." To be explicit: If this method returns a non-null value, 1096 * then: 1097 * 1098 * <ul> 1099 * <li>{@code isDone()} must return {@code true} 1100 * <li>{@code isCancelled()} must return {@code false} 1101 * <li>{@code get()} must not block, and it must throw an {@code ExecutionException} with the 1102 * return value of this method as its cause 1103 * </ul> 1104 * 1105 * <p>This method is {@code protected} so that classes like {@code 1106 * com.google.common.util.concurrent.SettableFuture} do not expose it to their users as an 1107 * instance method. In the unlikely event that you need to call this method, call {@link 1108 * InternalFutures#tryInternalFastPathGetFailure(InternalFutureFailureAccess)}. 1109 * 1110 * @since 27.0 1111 */ 1112 @Override 1113 /* 1114 * We should annotate the superclass, InternalFutureFailureAccess, to say that its copy of this 1115 * method returns @Nullable, too. However, we're not sure if we want to make any changes to that 1116 * class, since it's in a separate artifact that we planned to release only a single version of. 1117 */ 1118 @CheckForNull 1119 protected final Throwable tryInternalFastPathGetFailure() { 1120 if (this instanceof Trusted) { 1121 @RetainedLocalRef Object localValue = value; 1122 if (localValue instanceof Failure) { 1123 return ((Failure) localValue).exception; 1124 } 1125 } 1126 return null; 1127 } 1128 1129 /** 1130 * If this future has been cancelled (and possibly interrupted), cancels (and possibly interrupts) 1131 * the given future (if available). 1132 */ 1133 final void maybePropagateCancellationTo(@CheckForNull Future<?> related) { 1134 if (related != null & isCancelled()) { 1135 related.cancel(wasInterrupted()); 1136 } 1137 } 1138 1139 /** Releases all threads in the {@link #waiters} list, and clears the list. */ 1140 private void releaseWaiters() { 1141 Waiter head = ATOMIC_HELPER.gasWaiters(this, Waiter.TOMBSTONE); 1142 for (Waiter currentWaiter = head; currentWaiter != null; currentWaiter = currentWaiter.next) { 1143 currentWaiter.unpark(); 1144 } 1145 } 1146 1147 /** 1148 * Clears the {@link #listeners} list and prepends its contents to {@code onto}, least recently 1149 * added first. 1150 */ 1151 @CheckForNull 1152 private Listener clearListeners(@CheckForNull Listener onto) { 1153 // We need to 1154 // 1. atomically swap the listeners with TOMBSTONE, this is because addListener uses that 1155 // to synchronize with us 1156 // 2. reverse the linked list, because despite our rather clear contract, people depend on us 1157 // executing listeners in the order they were added 1158 // 3. push all the items onto 'onto' and return the new head of the stack 1159 Listener head = ATOMIC_HELPER.gasListeners(this, Listener.TOMBSTONE); 1160 Listener reversedList = onto; 1161 while (head != null) { 1162 Listener tmp = head; 1163 head = head.next; 1164 tmp.next = reversedList; 1165 reversedList = tmp; 1166 } 1167 return reversedList; 1168 } 1169 1170 // TODO(user): move parts into a default method on ListenableFuture? 1171 @Override 1172 public String toString() { 1173 // TODO(cpovirk): Presize to something plausible? 1174 StringBuilder builder = new StringBuilder(); 1175 if (getClass().getName().startsWith("com.google.common.util.concurrent.")) { 1176 builder.append(getClass().getSimpleName()); 1177 } else { 1178 builder.append(getClass().getName()); 1179 } 1180 builder.append('@').append(toHexString(identityHashCode(this))).append("[status="); 1181 if (isCancelled()) { 1182 builder.append("CANCELLED"); 1183 } else if (isDone()) { 1184 addDoneString(builder); 1185 } else { 1186 addPendingString(builder); // delegates to addDoneString if future completes midway 1187 } 1188 return builder.append("]").toString(); 1189 } 1190 1191 /** 1192 * Provide a human-readable explanation of why this future has not yet completed. 1193 * 1194 * @return null if an explanation cannot be provided (e.g. because the future is done). 1195 * @since 23.0 1196 */ 1197 @CheckForNull 1198 protected String pendingToString() { 1199 // TODO(diamondm) consider moving this into addPendingString so it's always in the output 1200 if (this instanceof ScheduledFuture) { 1201 return "remaining delay=[" + ((ScheduledFuture) this).getDelay(MILLISECONDS) + " ms]"; 1202 } 1203 return null; 1204 } 1205 1206 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 1207 private void addPendingString(StringBuilder builder) { 1208 // Capture current builder length so it can be truncated if this future ends up completing while 1209 // the toString is being calculated 1210 int truncateLength = builder.length(); 1211 1212 builder.append("PENDING"); 1213 1214 @RetainedLocalRef Object localValue = value; 1215 if (localValue instanceof SetFuture) { 1216 builder.append(", setFuture=["); 1217 appendUserObject(builder, ((SetFuture) localValue).future); 1218 builder.append("]"); 1219 } else { 1220 String pendingDescription; 1221 try { 1222 pendingDescription = Strings.emptyToNull(pendingToString()); 1223 } catch (Exception | StackOverflowError e) { 1224 // Any Exception is either a RuntimeException or sneaky checked exception. 1225 // 1226 // Don't call getMessage or toString() on the exception, in case the exception thrown by the 1227 // subclass is implemented with bugs similar to the subclass. 1228 pendingDescription = "Exception thrown from implementation: " + e.getClass(); 1229 } 1230 if (pendingDescription != null) { 1231 builder.append(", info=[").append(pendingDescription).append("]"); 1232 } 1233 } 1234 1235 // The future may complete while calculating the toString, so we check once more to see if the 1236 // future is done 1237 if (isDone()) { 1238 // Truncate anything that was appended before realizing this future is done 1239 builder.delete(truncateLength, builder.length()); 1240 addDoneString(builder); 1241 } 1242 } 1243 1244 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 1245 private void addDoneString(StringBuilder builder) { 1246 try { 1247 V value = getUninterruptibly(this); 1248 builder.append("SUCCESS, result=["); 1249 appendResultObject(builder, value); 1250 builder.append("]"); 1251 } catch (ExecutionException e) { 1252 builder.append("FAILURE, cause=[").append(e.getCause()).append("]"); 1253 } catch (CancellationException e) { 1254 builder.append("CANCELLED"); // shouldn't be reachable 1255 } catch (Exception e) { // sneaky checked exception 1256 builder.append("UNKNOWN, cause=[").append(e.getClass()).append(" thrown from get()]"); 1257 } 1258 } 1259 1260 /** 1261 * Any object can be the result of a Future, and not every object has a reasonable toString() 1262 * implementation. Using a reconstruction of the default Object.toString() prevents OOMs and stack 1263 * overflows, and helps avoid sensitive data inadvertently ending up in exception messages. 1264 */ 1265 private void appendResultObject(StringBuilder builder, @CheckForNull Object o) { 1266 if (o == null) { 1267 builder.append("null"); 1268 } else if (o == this) { 1269 builder.append("this future"); 1270 } else { 1271 builder 1272 .append(o.getClass().getName()) 1273 .append("@") 1274 .append(Integer.toHexString(System.identityHashCode(o))); 1275 } 1276 } 1277 1278 /** Helper for printing user supplied objects into our toString method. */ 1279 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 1280 private void appendUserObject(StringBuilder builder, @CheckForNull Object o) { 1281 // This is some basic recursion detection for when people create cycles via set/setFuture or 1282 // when deep chains of futures exist resulting in a StackOverflowException. We could detect 1283 // arbitrary cycles using a thread local but this should be a good enough solution (it is also 1284 // what jdk collections do in these cases) 1285 try { 1286 if (o == this) { 1287 builder.append("this future"); 1288 } else { 1289 builder.append(o); 1290 } 1291 } catch (Exception | StackOverflowError e) { 1292 // Any Exception is either a RuntimeException or sneaky checked exception. 1293 // 1294 // Don't call getMessage or toString() on the exception, in case the exception thrown by the 1295 // user object is implemented with bugs similar to the user object. 1296 builder.append("Exception thrown from implementation: ").append(e.getClass()); 1297 } 1298 } 1299 1300 /** 1301 * Submits the given runnable to the given {@link Executor} catching and logging all {@linkplain 1302 * RuntimeException runtime exceptions} thrown by the executor. 1303 */ 1304 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 1305 private static void executeListener(Runnable runnable, Executor executor) { 1306 try { 1307 executor.execute(runnable); 1308 } catch (Exception e) { // sneaky checked exception 1309 // Log it and keep going -- bad runnable and/or executor. Don't punish the other runnables if 1310 // we're given a bad one. We only catch Exception because we want Errors to propagate up. 1311 log.get() 1312 .log( 1313 Level.SEVERE, 1314 "RuntimeException while executing runnable " 1315 + runnable 1316 + " with executor " 1317 + executor, 1318 e); 1319 } 1320 } 1321 1322 private abstract static class AtomicHelper { 1323 /** Non-volatile write of the thread to the {@link Waiter#thread} field. */ 1324 abstract void putThread(Waiter waiter, Thread newValue); 1325 1326 /** Non-volatile write of the waiter to the {@link Waiter#next} field. */ 1327 abstract void putNext(Waiter waiter, @CheckForNull Waiter newValue); 1328 1329 /** Performs a CAS operation on the {@link AbstractFuture#waiters} field. */ 1330 abstract boolean casWaiters( 1331 AbstractFuture<?> future, @CheckForNull Waiter expect, @CheckForNull Waiter update); 1332 1333 /** Performs a CAS operation on the {@link AbstractFuture#listeners} field. */ 1334 abstract boolean casListeners( 1335 AbstractFuture<?> future, @CheckForNull Listener expect, Listener update); 1336 1337 /** Performs a GAS operation on the {@link AbstractFuture#waiters} field. */ 1338 abstract Waiter gasWaiters(AbstractFuture<?> future, Waiter update); 1339 1340 /** Performs a GAS operation on the {@link AbstractFuture#listeners} field. */ 1341 abstract Listener gasListeners(AbstractFuture<?> future, Listener update); 1342 1343 /** Performs a CAS operation on the {@link AbstractFuture#value} field. */ 1344 abstract boolean casValue(AbstractFuture<?> future, @CheckForNull Object expect, Object update); 1345 } 1346 1347 /** 1348 * {@link AtomicHelper} based on {@link sun.misc.Unsafe}. 1349 * 1350 * <p>Static initialization of this class will fail if the {@link sun.misc.Unsafe} object cannot 1351 * be accessed. 1352 */ 1353 @SuppressWarnings({"SunApi", "removal"}) // b/345822163 1354 private static final class UnsafeAtomicHelper extends AtomicHelper { 1355 static final Unsafe UNSAFE; 1356 static final long LISTENERS_OFFSET; 1357 static final long WAITERS_OFFSET; 1358 static final long VALUE_OFFSET; 1359 static final long WAITER_THREAD_OFFSET; 1360 static final long WAITER_NEXT_OFFSET; 1361 1362 static { 1363 Unsafe unsafe = null; 1364 try { 1365 unsafe = Unsafe.getUnsafe(); 1366 } catch (SecurityException tryReflectionInstead) { 1367 try { 1368 unsafe = 1369 AccessController.doPrivileged( 1370 new PrivilegedExceptionAction<Unsafe>() { 1371 @Override 1372 public Unsafe run() throws Exception { 1373 Class<Unsafe> k = Unsafe.class; 1374 for (Field f : k.getDeclaredFields()) { 1375 f.setAccessible(true); 1376 Object x = f.get(null); 1377 if (k.isInstance(x)) { 1378 return k.cast(x); 1379 } 1380 } 1381 throw new NoSuchFieldError("the Unsafe"); 1382 } 1383 }); 1384 } catch (PrivilegedActionException e) { 1385 throw new RuntimeException("Could not initialize intrinsics", e.getCause()); 1386 } 1387 } 1388 try { 1389 Class<?> abstractFuture = AbstractFuture.class; 1390 WAITERS_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("waiters")); 1391 LISTENERS_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("listeners")); 1392 VALUE_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("value")); 1393 WAITER_THREAD_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("thread")); 1394 WAITER_NEXT_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("next")); 1395 UNSAFE = unsafe; 1396 } catch (NoSuchFieldException e) { 1397 throw new RuntimeException(e); 1398 } 1399 } 1400 1401 @Override 1402 void putThread(Waiter waiter, Thread newValue) { 1403 UNSAFE.putObject(waiter, WAITER_THREAD_OFFSET, newValue); 1404 } 1405 1406 @Override 1407 void putNext(Waiter waiter, @CheckForNull Waiter newValue) { 1408 UNSAFE.putObject(waiter, WAITER_NEXT_OFFSET, newValue); 1409 } 1410 1411 @Override 1412 boolean casWaiters( 1413 AbstractFuture<?> future, @CheckForNull Waiter expect, @CheckForNull Waiter update) { 1414 return UNSAFE.compareAndSwapObject(future, WAITERS_OFFSET, expect, update); 1415 } 1416 1417 @Override 1418 boolean casListeners(AbstractFuture<?> future, @CheckForNull Listener expect, Listener update) { 1419 return UNSAFE.compareAndSwapObject(future, LISTENERS_OFFSET, expect, update); 1420 } 1421 1422 @Override 1423 Listener gasListeners(AbstractFuture<?> future, Listener update) { 1424 return (Listener) UNSAFE.getAndSetObject(future, LISTENERS_OFFSET, update); 1425 } 1426 1427 @Override 1428 Waiter gasWaiters(AbstractFuture<?> future, Waiter update) { 1429 return (Waiter) UNSAFE.getAndSetObject(future, WAITERS_OFFSET, update); 1430 } 1431 1432 @Override 1433 boolean casValue(AbstractFuture<?> future, @CheckForNull Object expect, Object update) { 1434 return UNSAFE.compareAndSwapObject(future, VALUE_OFFSET, expect, update); 1435 } 1436 } 1437 1438 /** {@link AtomicHelper} based on {@link AtomicReferenceFieldUpdater}. */ 1439 private static final class AtomicReferenceFieldUpdaterAtomicHelper extends AtomicHelper { 1440 final AtomicReferenceFieldUpdater<Waiter, Thread> waiterThreadUpdater; 1441 final AtomicReferenceFieldUpdater<Waiter, Waiter> waiterNextUpdater; 1442 final AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Waiter> waitersUpdater; 1443 final AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Listener> listenersUpdater; 1444 final AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Object> valueUpdater; 1445 1446 AtomicReferenceFieldUpdaterAtomicHelper( 1447 AtomicReferenceFieldUpdater<Waiter, Thread> waiterThreadUpdater, 1448 AtomicReferenceFieldUpdater<Waiter, Waiter> waiterNextUpdater, 1449 AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Waiter> waitersUpdater, 1450 AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Listener> listenersUpdater, 1451 AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Object> valueUpdater) { 1452 this.waiterThreadUpdater = waiterThreadUpdater; 1453 this.waiterNextUpdater = waiterNextUpdater; 1454 this.waitersUpdater = waitersUpdater; 1455 this.listenersUpdater = listenersUpdater; 1456 this.valueUpdater = valueUpdater; 1457 } 1458 1459 @Override 1460 void putThread(Waiter waiter, Thread newValue) { 1461 waiterThreadUpdater.lazySet(waiter, newValue); 1462 } 1463 1464 @Override 1465 void putNext(Waiter waiter, @CheckForNull Waiter newValue) { 1466 waiterNextUpdater.lazySet(waiter, newValue); 1467 } 1468 1469 @Override 1470 boolean casWaiters( 1471 AbstractFuture<?> future, @CheckForNull Waiter expect, @CheckForNull Waiter update) { 1472 return waitersUpdater.compareAndSet(future, expect, update); 1473 } 1474 1475 @Override 1476 boolean casListeners(AbstractFuture<?> future, @CheckForNull Listener expect, Listener update) { 1477 return listenersUpdater.compareAndSet(future, expect, update); 1478 } 1479 1480 @Override 1481 Listener gasListeners(AbstractFuture<?> future, Listener update) { 1482 return listenersUpdater.getAndSet(future, update); 1483 } 1484 1485 @Override 1486 Waiter gasWaiters(AbstractFuture<?> future, Waiter update) { 1487 return waitersUpdater.getAndSet(future, update); 1488 } 1489 1490 @Override 1491 boolean casValue(AbstractFuture<?> future, @CheckForNull Object expect, Object update) { 1492 return valueUpdater.compareAndSet(future, expect, update); 1493 } 1494 } 1495 1496 /** 1497 * {@link AtomicHelper} based on {@code synchronized} and volatile writes. 1498 * 1499 * <p>This is an implementation of last resort for when certain basic VM features are broken (like 1500 * AtomicReferenceFieldUpdater). 1501 */ 1502 private static final class SynchronizedHelper extends AtomicHelper { 1503 @Override 1504 void putThread(Waiter waiter, Thread newValue) { 1505 waiter.thread = newValue; 1506 } 1507 1508 @Override 1509 void putNext(Waiter waiter, @CheckForNull Waiter newValue) { 1510 waiter.next = newValue; 1511 } 1512 1513 @Override 1514 boolean casWaiters( 1515 AbstractFuture<?> future, @CheckForNull Waiter expect, @CheckForNull Waiter update) { 1516 synchronized (future) { 1517 if (future.waiters == expect) { 1518 future.waiters = update; 1519 return true; 1520 } 1521 return false; 1522 } 1523 } 1524 1525 @Override 1526 boolean casListeners(AbstractFuture<?> future, @CheckForNull Listener expect, Listener update) { 1527 synchronized (future) { 1528 if (future.listeners == expect) { 1529 future.listeners = update; 1530 return true; 1531 } 1532 return false; 1533 } 1534 } 1535 1536 @Override 1537 Listener gasListeners(AbstractFuture<?> future, Listener update) { 1538 synchronized (future) { 1539 Listener old = future.listeners; 1540 if (old != update) { 1541 future.listeners = update; 1542 } 1543 return old; 1544 } 1545 } 1546 1547 @Override 1548 Waiter gasWaiters(AbstractFuture<?> future, Waiter update) { 1549 synchronized (future) { 1550 Waiter old = future.waiters; 1551 if (old != update) { 1552 future.waiters = update; 1553 } 1554 return old; 1555 } 1556 } 1557 1558 @Override 1559 boolean casValue(AbstractFuture<?> future, @CheckForNull Object expect, Object update) { 1560 synchronized (future) { 1561 if (future.value == expect) { 1562 future.value = update; 1563 return true; 1564 } 1565 return false; 1566 } 1567 } 1568 } 1569 1570 private static CancellationException cancellationExceptionWithCause( 1571 String message, @CheckForNull Throwable cause) { 1572 CancellationException exception = new CancellationException(message); 1573 exception.initCause(cause); 1574 return exception; 1575 } 1576}