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