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 @SuppressWarnings("LabelledBreakTarget") // TODO(b/345814817): Maybe fix? 433 @CanIgnoreReturnValue 434 @Override 435 @ParametricNullness 436 public V get(long timeout, TimeUnit unit) 437 throws InterruptedException, TimeoutException, ExecutionException { 438 // NOTE: if timeout < 0, remainingNanos will be < 0 and we will fall into the while(true) loop 439 // at the bottom and throw a timeoutexception. 440 final long timeoutNanos = unit.toNanos(timeout); // we rely on the implicit null check on unit. 441 long remainingNanos = timeoutNanos; 442 if (Thread.interrupted()) { 443 throw new InterruptedException(); 444 } 445 Object localValue = value; 446 if (localValue != null & !(localValue instanceof SetFuture)) { 447 return getDoneValue(localValue); 448 } 449 // we delay calling nanoTime until we know we will need to either park or spin 450 final long endNanos = remainingNanos > 0 ? System.nanoTime() + remainingNanos : 0; 451 long_wait_loop: 452 if (remainingNanos >= SPIN_THRESHOLD_NANOS) { 453 Waiter oldHead = waiters; 454 if (oldHead != Waiter.TOMBSTONE) { 455 Waiter node = new Waiter(); 456 do { 457 node.setNext(oldHead); 458 if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) { 459 while (true) { 460 OverflowAvoidingLockSupport.parkNanos(this, remainingNanos); 461 // Check interruption first, if we woke up due to interruption we need to honor that. 462 if (Thread.interrupted()) { 463 removeWaiter(node); 464 throw new InterruptedException(); 465 } 466 467 // Otherwise re-read and check doneness. If we loop then it must have been a spurious 468 // wakeup 469 localValue = value; 470 if (localValue != null & !(localValue instanceof SetFuture)) { 471 return getDoneValue(localValue); 472 } 473 474 // timed out? 475 remainingNanos = endNanos - System.nanoTime(); 476 if (remainingNanos < SPIN_THRESHOLD_NANOS) { 477 // Remove the waiter, one way or another we are done parking this thread. 478 removeWaiter(node); 479 break long_wait_loop; // jump down to the busy wait loop 480 } 481 } 482 } 483 oldHead = waiters; // re-read and loop. 484 } while (oldHead != Waiter.TOMBSTONE); 485 } 486 // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a 487 // waiter. 488 // requireNonNull is safe because value is always set before TOMBSTONE. 489 return getDoneValue(requireNonNull(value)); 490 } 491 // If we get here then we have remainingNanos < SPIN_THRESHOLD_NANOS and there is no node on the 492 // waiters list 493 while (remainingNanos > 0) { 494 localValue = value; 495 if (localValue != null & !(localValue instanceof SetFuture)) { 496 return getDoneValue(localValue); 497 } 498 if (Thread.interrupted()) { 499 throw new InterruptedException(); 500 } 501 remainingNanos = endNanos - System.nanoTime(); 502 } 503 504 String futureToString = toString(); 505 final String unitString = unit.toString().toLowerCase(Locale.ROOT); 506 String message = "Waited " + timeout + " " + unit.toString().toLowerCase(Locale.ROOT); 507 // Only report scheduling delay if larger than our spin threshold - otherwise it's just noise 508 if (remainingNanos + SPIN_THRESHOLD_NANOS < 0) { 509 // We over-waited for our timeout. 510 message += " (plus "; 511 long overWaitNanos = -remainingNanos; 512 long overWaitUnits = unit.convert(overWaitNanos, TimeUnit.NANOSECONDS); 513 long overWaitLeftoverNanos = overWaitNanos - unit.toNanos(overWaitUnits); 514 boolean shouldShowExtraNanos = 515 overWaitUnits == 0 || overWaitLeftoverNanos > SPIN_THRESHOLD_NANOS; 516 if (overWaitUnits > 0) { 517 message += overWaitUnits + " " + unitString; 518 if (shouldShowExtraNanos) { 519 message += ","; 520 } 521 message += " "; 522 } 523 if (shouldShowExtraNanos) { 524 message += overWaitLeftoverNanos + " nanoseconds "; 525 } 526 527 message += "delay)"; 528 } 529 // It's confusing to see a completed future in a timeout message; if isDone() returns false, 530 // then we know it must have given a pending toString value earlier. If not, then the future 531 // completed after the timeout expired, and the message might be success. 532 if (isDone()) { 533 throw new TimeoutException(message + " but future completed as timeout expired"); 534 } 535 throw new TimeoutException(message + " for " + futureToString); 536 } 537 538 /** 539 * {@inheritDoc} 540 * 541 * <p>The default {@link AbstractFuture} implementation throws {@code InterruptedException} if the 542 * current thread is interrupted during the call, even if the value is already available. 543 * 544 * @throws CancellationException {@inheritDoc} 545 */ 546 @CanIgnoreReturnValue 547 @Override 548 @ParametricNullness 549 public V get() throws InterruptedException, ExecutionException { 550 if (Thread.interrupted()) { 551 throw new InterruptedException(); 552 } 553 Object localValue = value; 554 if (localValue != null & !(localValue instanceof SetFuture)) { 555 return getDoneValue(localValue); 556 } 557 Waiter oldHead = waiters; 558 if (oldHead != Waiter.TOMBSTONE) { 559 Waiter node = new Waiter(); 560 do { 561 node.setNext(oldHead); 562 if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) { 563 // we are on the stack, now wait for completion. 564 while (true) { 565 LockSupport.park(this); 566 // Check interruption first, if we woke up due to interruption we need to honor that. 567 if (Thread.interrupted()) { 568 removeWaiter(node); 569 throw new InterruptedException(); 570 } 571 // Otherwise re-read and check doneness. If we loop then it must have been a spurious 572 // wakeup 573 localValue = value; 574 if (localValue != null & !(localValue instanceof SetFuture)) { 575 return getDoneValue(localValue); 576 } 577 } 578 } 579 oldHead = waiters; // re-read and loop. 580 } while (oldHead != Waiter.TOMBSTONE); 581 } 582 // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a 583 // waiter. 584 // requireNonNull is safe because value is always set before TOMBSTONE. 585 return getDoneValue(requireNonNull(value)); 586 } 587 588 /** Unboxes {@code obj}. Assumes that obj is not {@code null} or a {@link SetFuture}. */ 589 @ParametricNullness 590 private V getDoneValue(Object obj) throws ExecutionException { 591 // While this seems like it might be too branch-y, simple benchmarking proves it to be 592 // unmeasurable (comparing done AbstractFutures with immediateFuture) 593 if (obj instanceof Cancellation) { 594 throw cancellationExceptionWithCause("Task was cancelled.", ((Cancellation) obj).cause); 595 } else if (obj instanceof Failure) { 596 throw new ExecutionException(((Failure) obj).exception); 597 } else if (obj == NULL) { 598 /* 599 * It's safe to return null because we would only have stored it in the first place if it were 600 * a valid value for V. 601 */ 602 return uncheckedNull(); 603 } else { 604 @SuppressWarnings("unchecked") // this is the only other option 605 V asV = (V) obj; 606 return asV; 607 } 608 } 609 610 @Override 611 public boolean isDone() { 612 final Object localValue = value; 613 return localValue != null & !(localValue instanceof SetFuture); 614 } 615 616 @Override 617 public boolean isCancelled() { 618 final Object localValue = value; 619 return localValue instanceof Cancellation; 620 } 621 622 /** 623 * {@inheritDoc} 624 * 625 * <p>If a cancellation attempt succeeds on a {@code Future} that had previously been {@linkplain 626 * #setFuture set asynchronously}, then the cancellation will also be propagated to the delegate 627 * {@code Future} that was supplied in the {@code setFuture} call. 628 * 629 * <p>Rather than override this method to perform additional cancellation work or cleanup, 630 * subclasses should override {@link #afterDone}, consulting {@link #isCancelled} and {@link 631 * #wasInterrupted} as necessary. This ensures that the work is done even if the future is 632 * cancelled without a call to {@code cancel}, such as by calling {@code 633 * setFuture(cancelledFuture)}. 634 * 635 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 636 * acquire other locks, risking deadlocks. 637 */ 638 @CanIgnoreReturnValue 639 @Override 640 public boolean cancel(boolean mayInterruptIfRunning) { 641 Object localValue = value; 642 boolean rValue = false; 643 if (localValue == null | localValue instanceof SetFuture) { 644 // Try to delay allocating the exception. At this point we may still lose the CAS, but it is 645 // certainly less likely. 646 Object valueToSet = 647 GENERATE_CANCELLATION_CAUSES 648 ? new Cancellation( 649 mayInterruptIfRunning, new CancellationException("Future.cancel() was called.")) 650 /* 651 * requireNonNull is safe because we've initialized these if 652 * !GENERATE_CANCELLATION_CAUSES. 653 * 654 * TODO(cpovirk): Maybe it would be cleaner to define a CancellationSupplier interface 655 * with two implementations, one that contains causeless Cancellation instances and 656 * the other of which creates new Cancellation instances each time it's called? Yet 657 * another alternative is to fill in a non-null value for each of the fields no matter 658 * what and to just not use it if !GENERATE_CANCELLATION_CAUSES. 659 */ 660 : requireNonNull( 661 mayInterruptIfRunning 662 ? Cancellation.CAUSELESS_INTERRUPTED 663 : Cancellation.CAUSELESS_CANCELLED); 664 AbstractFuture<?> abstractFuture = this; 665 while (true) { 666 if (ATOMIC_HELPER.casValue(abstractFuture, localValue, valueToSet)) { 667 rValue = true; 668 complete(abstractFuture, mayInterruptIfRunning); 669 if (localValue instanceof SetFuture) { 670 // propagate cancellation to the future set in setfuture, this is racy, and we don't 671 // care if we are successful or not. 672 ListenableFuture<?> futureToPropagateTo = ((SetFuture) localValue).future; 673 if (futureToPropagateTo instanceof Trusted) { 674 // If the future is a TrustedFuture then we specifically avoid calling cancel() 675 // this has 2 benefits 676 // 1. for long chains of futures strung together with setFuture we consume less stack 677 // 2. we avoid allocating Cancellation objects at every level of the cancellation 678 // chain 679 // We can only do this for TrustedFuture, because TrustedFuture.cancel is final and 680 // does nothing but delegate to this method. 681 AbstractFuture<?> trusted = (AbstractFuture<?>) futureToPropagateTo; 682 localValue = trusted.value; 683 if (localValue == null | localValue instanceof SetFuture) { 684 abstractFuture = trusted; 685 continue; // loop back up and try to complete the new future 686 } 687 } else { 688 // not a TrustedFuture, call cancel directly. 689 futureToPropagateTo.cancel(mayInterruptIfRunning); 690 } 691 } 692 break; 693 } 694 // obj changed, reread 695 localValue = abstractFuture.value; 696 if (!(localValue instanceof SetFuture)) { 697 // obj cannot be null at this point, because value can only change from null to non-null. 698 // So if value changed (and it did since we lost the CAS), then it cannot be null and 699 // since it isn't a SetFuture, then the future must be done and we should exit the loop 700 break; 701 } 702 } 703 } 704 return rValue; 705 } 706 707 /** 708 * Subclasses can override this method to implement interruption of the future's computation. The 709 * method is invoked automatically by a successful call to {@link #cancel(boolean) cancel(true)}. 710 * 711 * <p>The default implementation does nothing. 712 * 713 * <p>This method is likely to be deprecated. Prefer to override {@link #afterDone}, consulting 714 * {@link #wasInterrupted} to decide whether to interrupt your task. 715 * 716 * @since 10.0 717 */ 718 protected void interruptTask() {} 719 720 /** 721 * Returns true if this future was cancelled with {@code mayInterruptIfRunning} set to {@code 722 * true}. 723 * 724 * @since 14.0 725 */ 726 protected final boolean wasInterrupted() { 727 final Object localValue = value; 728 return (localValue instanceof Cancellation) && ((Cancellation) localValue).wasInterrupted; 729 } 730 731 /** 732 * {@inheritDoc} 733 * 734 * @since 10.0 735 */ 736 @Override 737 public void addListener(Runnable listener, Executor executor) { 738 checkNotNull(listener, "Runnable was null."); 739 checkNotNull(executor, "Executor was null."); 740 // Checking isDone and listeners != TOMBSTONE may seem redundant, but our contract for 741 // addListener says that listeners execute 'immediate' if the future isDone(). However, our 742 // protocol for completing a future is to assign the value field (which sets isDone to true) and 743 // then to release waiters, followed by executing afterDone(), followed by releasing listeners. 744 // That means that it is possible to observe that the future isDone and that your listeners 745 // don't execute 'immediately'. By checking isDone here we avoid that. 746 // A corollary to all that is that we don't need to check isDone inside the loop because if we 747 // get into the loop we know that we weren't done when we entered and therefore we aren't under 748 // an obligation to execute 'immediately'. 749 if (!isDone()) { 750 Listener oldHead = listeners; 751 if (oldHead != Listener.TOMBSTONE) { 752 Listener newNode = new Listener(listener, executor); 753 do { 754 newNode.next = oldHead; 755 if (ATOMIC_HELPER.casListeners(this, oldHead, newNode)) { 756 return; 757 } 758 oldHead = listeners; // re-read 759 } while (oldHead != Listener.TOMBSTONE); 760 } 761 } 762 // If we get here then the Listener TOMBSTONE was set, which means the future is done, call 763 // the listener. 764 executeListener(listener, executor); 765 } 766 767 /** 768 * Sets the result of this {@code Future} unless this {@code Future} has already been cancelled or 769 * set (including {@linkplain #setFuture set asynchronously}). When a call to this method returns, 770 * the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> the call was 771 * accepted (in which case it returns {@code true}). If it returns {@code false}, the {@code 772 * Future} may have previously been set asynchronously, in which case its result may not be known 773 * yet. That result, though not yet known, cannot be overridden by a call to a {@code set*} 774 * method, only by a call to {@link #cancel}. 775 * 776 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 777 * acquire other locks, risking deadlocks. 778 * 779 * @param value the value to be used as the result 780 * @return true if the attempt was accepted, completing the {@code Future} 781 */ 782 @CanIgnoreReturnValue 783 protected boolean set(@ParametricNullness V value) { 784 Object valueToSet = value == null ? NULL : value; 785 if (ATOMIC_HELPER.casValue(this, null, valueToSet)) { 786 complete(this, /*callInterruptTask=*/ false); 787 return true; 788 } 789 return false; 790 } 791 792 /** 793 * Sets the failed result of this {@code Future} unless this {@code Future} has already been 794 * cancelled or set (including {@linkplain #setFuture set asynchronously}). When a call to this 795 * method returns, the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> 796 * the call was accepted (in which case it returns {@code true}). If it returns {@code false}, the 797 * {@code Future} may have previously been set asynchronously, in which case its result may not be 798 * known yet. That result, though not yet known, cannot be overridden by a call to a {@code set*} 799 * method, only by a call to {@link #cancel}. 800 * 801 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 802 * acquire other locks, risking deadlocks. 803 * 804 * @param throwable the exception to be used as the failed result 805 * @return true if the attempt was accepted, completing the {@code Future} 806 */ 807 @CanIgnoreReturnValue 808 protected boolean setException(Throwable throwable) { 809 Object valueToSet = new Failure(checkNotNull(throwable)); 810 if (ATOMIC_HELPER.casValue(this, null, valueToSet)) { 811 complete(this, /*callInterruptTask=*/ false); 812 return true; 813 } 814 return false; 815 } 816 817 /** 818 * Sets the result of this {@code Future} to match the supplied input {@code Future} once the 819 * supplied {@code Future} is done, unless this {@code Future} has already been cancelled or set 820 * (including "set asynchronously," defined below). 821 * 822 * <p>If the supplied future is {@linkplain #isDone done} when this method is called and the call 823 * is accepted, then this future is guaranteed to have been completed with the supplied future by 824 * the time this method returns. If the supplied future is not done and the call is accepted, then 825 * the future will be <i>set asynchronously</i>. Note that such a result, though not yet known, 826 * cannot be overridden by a call to a {@code set*} method, only by a call to {@link #cancel}. 827 * 828 * <p>If the call {@code setFuture(delegate)} is accepted and this {@code Future} is later 829 * cancelled, cancellation will be propagated to {@code delegate}. Additionally, any call to 830 * {@code setFuture} after any cancellation will propagate cancellation to the supplied {@code 831 * Future}. 832 * 833 * <p>Note that, even if the supplied future is cancelled and it causes this future to complete, 834 * it will never trigger interruption behavior. In particular, it will not cause this future to 835 * invoke the {@link #interruptTask} method, and the {@link #wasInterrupted} method will not 836 * return {@code true}. 837 * 838 * <p>Beware of completing a future while holding a lock. Its listeners may do slow work or 839 * acquire other locks, risking deadlocks. 840 * 841 * @param future the future to delegate to 842 * @return true if the attempt was accepted, indicating that the {@code Future} was not previously 843 * cancelled or set. 844 * @since 19.0 845 */ 846 @CanIgnoreReturnValue 847 protected boolean setFuture(ListenableFuture<? extends V> future) { 848 checkNotNull(future); 849 Object localValue = value; 850 if (localValue == null) { 851 if (future.isDone()) { 852 Object value = getFutureValue(future); 853 if (ATOMIC_HELPER.casValue(this, null, value)) { 854 complete( 855 this, 856 /* 857 * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so 858 * don't invoke interruptTask. 859 */ 860 false); 861 return true; 862 } 863 return false; 864 } 865 SetFuture<V> valueToSet = new SetFuture<>(this, future); 866 if (ATOMIC_HELPER.casValue(this, null, valueToSet)) { 867 // the listener is responsible for calling completeWithFuture, directExecutor is appropriate 868 // since all we are doing is unpacking a completed future which should be fast. 869 try { 870 future.addListener(valueToSet, DirectExecutor.INSTANCE); 871 } catch (Throwable t) { 872 // Any Exception is either a RuntimeException or sneaky checked exception. 873 // 874 // addListener has thrown an exception! SetFuture.run can't throw any exceptions so this 875 // must have been caused by addListener itself. The most likely explanation is a 876 // misconfigured mock. Try to switch to Failure. 877 Failure failure; 878 try { 879 failure = new Failure(t); 880 } catch (Exception | Error oomMostLikely) { // sneaky checked exception 881 failure = Failure.FALLBACK_INSTANCE; 882 } 883 // Note: The only way this CAS could fail is if cancel() has raced with us. That is ok. 884 boolean unused = ATOMIC_HELPER.casValue(this, valueToSet, failure); 885 } 886 return true; 887 } 888 localValue = value; // we lost the cas, fall through and maybe cancel 889 } 890 // The future has already been set to something. If it is cancellation we should cancel the 891 // incoming future. 892 if (localValue instanceof Cancellation) { 893 // we don't care if it fails, this is best-effort. 894 future.cancel(((Cancellation) localValue).wasInterrupted); 895 } 896 return false; 897 } 898 899 /** 900 * Returns a value that satisfies the contract of the {@link #value} field based on the state of 901 * given future. 902 * 903 * <p>This is approximately the inverse of {@link #getDoneValue(Object)} 904 */ 905 private static Object getFutureValue(ListenableFuture<?> future) { 906 if (future instanceof Trusted) { 907 // Break encapsulation for TrustedFuture instances since we know that subclasses cannot 908 // override .get() (since it is final) and therefore this is equivalent to calling .get() 909 // and unpacking the exceptions like we do below (just much faster because it is a single 910 // field read instead of a read, several branches and possibly creating exceptions). 911 Object v = ((AbstractFuture<?>) future).value; 912 if (v instanceof Cancellation) { 913 // If the other future was interrupted, clear the interrupted bit while preserving the cause 914 // this will make it consistent with how non-trustedfutures work which cannot propagate the 915 // wasInterrupted bit 916 Cancellation c = (Cancellation) v; 917 if (c.wasInterrupted) { 918 v = 919 c.cause != null 920 ? new Cancellation(/* wasInterrupted= */ false, c.cause) 921 : Cancellation.CAUSELESS_CANCELLED; 922 } 923 } 924 // requireNonNull is safe as long as we call this method only on completed futures. 925 return requireNonNull(v); 926 } 927 if (future instanceof InternalFutureFailureAccess) { 928 Throwable throwable = 929 InternalFutures.tryInternalFastPathGetFailure((InternalFutureFailureAccess) future); 930 if (throwable != null) { 931 return new Failure(throwable); 932 } 933 } 934 boolean wasCancelled = future.isCancelled(); 935 // Don't allocate a CancellationException if it's not necessary 936 if (!GENERATE_CANCELLATION_CAUSES & wasCancelled) { 937 /* 938 * requireNonNull is safe because we've initialized CAUSELESS_CANCELLED if 939 * !GENERATE_CANCELLATION_CAUSES. 940 */ 941 return requireNonNull(Cancellation.CAUSELESS_CANCELLED); 942 } 943 // Otherwise calculate the value by calling .get() 944 try { 945 Object v = getUninterruptibly(future); 946 if (wasCancelled) { 947 return new Cancellation( 948 false, 949 new IllegalArgumentException( 950 "get() did not throw CancellationException, despite reporting " 951 + "isCancelled() == true: " 952 + future)); 953 } 954 return v == null ? NULL : v; 955 } catch (ExecutionException exception) { 956 if (wasCancelled) { 957 return new Cancellation( 958 false, 959 new IllegalArgumentException( 960 "get() did not throw CancellationException, despite reporting " 961 + "isCancelled() == true: " 962 + future, 963 exception)); 964 } 965 return new Failure(exception.getCause()); 966 } catch (CancellationException cancellation) { 967 if (!wasCancelled) { 968 return new Failure( 969 new IllegalArgumentException( 970 "get() threw CancellationException, despite reporting isCancelled() == false: " 971 + future, 972 cancellation)); 973 } 974 return new Cancellation(false, cancellation); 975 } catch (Exception | Error t) { // sneaky checked exception 976 return new Failure(t); 977 } 978 } 979 980 /** 981 * An inlined private copy of {@link Uninterruptibles#getUninterruptibly} used to break an 982 * internal dependency on other /util/concurrent classes. 983 */ 984 @ParametricNullness 985 private static <V extends @Nullable Object> V getUninterruptibly(Future<V> future) 986 throws ExecutionException { 987 boolean interrupted = false; 988 try { 989 while (true) { 990 try { 991 return future.get(); 992 } catch (InterruptedException e) { 993 interrupted = true; 994 } 995 } 996 } finally { 997 if (interrupted) { 998 Thread.currentThread().interrupt(); 999 } 1000 } 1001 } 1002 1003 /** Unblocks all threads and runs all listeners. */ 1004 private static void complete(AbstractFuture<?> param, boolean callInterruptTask) { 1005 // Declare a "true" local variable so that the Checker Framework will infer nullness. 1006 AbstractFuture<?> future = param; 1007 1008 Listener next = null; 1009 outer: 1010 while (true) { 1011 future.releaseWaiters(); 1012 /* 1013 * We call interruptTask() immediately before afterDone() so that migrating between the two 1014 * can be a no-op. 1015 */ 1016 if (callInterruptTask) { 1017 future.interruptTask(); 1018 /* 1019 * Interruption doesn't propagate through a SetFuture chain (see getFutureValue), so don't 1020 * invoke interruptTask on any subsequent futures. 1021 */ 1022 callInterruptTask = false; 1023 } 1024 // We call this before the listeners in order to avoid needing to manage a separate stack data 1025 // structure for them. Also, some implementations rely on this running prior to listeners 1026 // so that the cleanup work is visible to listeners. 1027 // afterDone() should be generally fast and only used for cleanup work... but in theory can 1028 // also be recursive and create StackOverflowErrors 1029 future.afterDone(); 1030 // push the current set of listeners onto next 1031 next = future.clearListeners(next); 1032 future = null; 1033 while (next != null) { 1034 Listener curr = next; 1035 next = next.next; 1036 /* 1037 * requireNonNull is safe because the listener stack never contains TOMBSTONE until after 1038 * clearListeners. 1039 */ 1040 Runnable task = requireNonNull(curr.task); 1041 if (task instanceof SetFuture) { 1042 SetFuture<?> setFuture = (SetFuture<?>) task; 1043 // We unwind setFuture specifically to avoid StackOverflowErrors in the case of long 1044 // chains of SetFutures 1045 // Handling this special case is important because there is no way to pass an executor to 1046 // setFuture, so a user couldn't break the chain by doing this themselves. It is also 1047 // potentially common if someone writes a recursive Futures.transformAsync transformer. 1048 future = setFuture.owner; 1049 if (future.value == setFuture) { 1050 Object valueToSet = getFutureValue(setFuture.future); 1051 if (ATOMIC_HELPER.casValue(future, setFuture, valueToSet)) { 1052 continue outer; 1053 } 1054 } 1055 // otherwise the future we were trying to set is already done. 1056 } else { 1057 /* 1058 * requireNonNull is safe because the listener stack never contains TOMBSTONE until after 1059 * clearListeners. 1060 */ 1061 executeListener(task, requireNonNull(curr.executor)); 1062 } 1063 } 1064 break; 1065 } 1066 } 1067 1068 /** 1069 * Callback method that is called exactly once after the future is completed. 1070 * 1071 * <p>If {@link #interruptTask} is also run during completion, {@link #afterDone} runs after it. 1072 * 1073 * <p>The default implementation of this method in {@code AbstractFuture} does nothing. This is 1074 * intended for very lightweight cleanup work, for example, timing statistics or clearing fields. 1075 * If your task does anything heavier consider, just using a listener with an executor. 1076 * 1077 * @since 20.0 1078 */ 1079 @ForOverride 1080 protected void afterDone() {} 1081 1082 // TODO(b/114236866): Inherit doc from InternalFutureFailureAccess. Also, -link to its URL. 1083 /** 1084 * Usually returns {@code null} but, if this {@code Future} has failed, may <i>optionally</i> 1085 * return the cause of the failure. "Failure" means specifically "completed with an exception"; it 1086 * does not include "was cancelled." To be explicit: If this method returns a non-null value, 1087 * then: 1088 * 1089 * <ul> 1090 * <li>{@code isDone()} must return {@code true} 1091 * <li>{@code isCancelled()} must return {@code false} 1092 * <li>{@code get()} must not block, and it must throw an {@code ExecutionException} with the 1093 * return value of this method as its cause 1094 * </ul> 1095 * 1096 * <p>This method is {@code protected} so that classes like {@code 1097 * com.google.common.util.concurrent.SettableFuture} do not expose it to their users as an 1098 * instance method. In the unlikely event that you need to call this method, call {@link 1099 * InternalFutures#tryInternalFastPathGetFailure(InternalFutureFailureAccess)}. 1100 * 1101 * @since 27.0 1102 */ 1103 @Override 1104 /* 1105 * We should annotate the superclass, InternalFutureFailureAccess, to say that its copy of this 1106 * method returns @Nullable, too. However, we're not sure if we want to make any changes to that 1107 * class, since it's in a separate artifact that we planned to release only a single version of. 1108 */ 1109 @CheckForNull 1110 protected final Throwable tryInternalFastPathGetFailure() { 1111 if (this instanceof Trusted) { 1112 Object obj = value; 1113 if (obj instanceof Failure) { 1114 return ((Failure) obj).exception; 1115 } 1116 } 1117 return null; 1118 } 1119 1120 /** 1121 * If this future has been cancelled (and possibly interrupted), cancels (and possibly interrupts) 1122 * the given future (if available). 1123 */ 1124 final void maybePropagateCancellationTo(@CheckForNull Future<?> related) { 1125 if (related != null & isCancelled()) { 1126 related.cancel(wasInterrupted()); 1127 } 1128 } 1129 1130 /** Releases all threads in the {@link #waiters} list, and clears the list. */ 1131 private void releaseWaiters() { 1132 Waiter head = ATOMIC_HELPER.gasWaiters(this, Waiter.TOMBSTONE); 1133 for (Waiter currentWaiter = head; currentWaiter != null; currentWaiter = currentWaiter.next) { 1134 currentWaiter.unpark(); 1135 } 1136 } 1137 1138 /** 1139 * Clears the {@link #listeners} list and prepends its contents to {@code onto}, least recently 1140 * added first. 1141 */ 1142 @CheckForNull 1143 private Listener clearListeners(@CheckForNull Listener onto) { 1144 // We need to 1145 // 1. atomically swap the listeners with TOMBSTONE, this is because addListener uses that 1146 // to synchronize with us 1147 // 2. reverse the linked list, because despite our rather clear contract, people depend on us 1148 // executing listeners in the order they were added 1149 // 3. push all the items onto 'onto' and return the new head of the stack 1150 Listener head = ATOMIC_HELPER.gasListeners(this, Listener.TOMBSTONE); 1151 Listener reversedList = onto; 1152 while (head != null) { 1153 Listener tmp = head; 1154 head = head.next; 1155 tmp.next = reversedList; 1156 reversedList = tmp; 1157 } 1158 return reversedList; 1159 } 1160 1161 // TODO(user): move parts into a default method on ListenableFuture? 1162 @Override 1163 public String toString() { 1164 // TODO(cpovirk): Presize to something plausible? 1165 StringBuilder builder = new StringBuilder(); 1166 if (getClass().getName().startsWith("com.google.common.util.concurrent.")) { 1167 builder.append(getClass().getSimpleName()); 1168 } else { 1169 builder.append(getClass().getName()); 1170 } 1171 builder.append('@').append(toHexString(identityHashCode(this))).append("[status="); 1172 if (isCancelled()) { 1173 builder.append("CANCELLED"); 1174 } else if (isDone()) { 1175 addDoneString(builder); 1176 } else { 1177 addPendingString(builder); // delegates to addDoneString if future completes midway 1178 } 1179 return builder.append("]").toString(); 1180 } 1181 1182 /** 1183 * Provide a human-readable explanation of why this future has not yet completed. 1184 * 1185 * @return null if an explanation cannot be provided (e.g. because the future is done). 1186 * @since 23.0 1187 */ 1188 @CheckForNull 1189 protected String pendingToString() { 1190 // TODO(diamondm) consider moving this into addPendingString so it's always in the output 1191 if (this instanceof ScheduledFuture) { 1192 return "remaining delay=[" 1193 + ((ScheduledFuture) this).getDelay(TimeUnit.MILLISECONDS) 1194 + " ms]"; 1195 } 1196 return null; 1197 } 1198 1199 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 1200 private void addPendingString(StringBuilder builder) { 1201 // Capture current builder length so it can be truncated if this future ends up completing while 1202 // the toString is being calculated 1203 int truncateLength = builder.length(); 1204 1205 builder.append("PENDING"); 1206 1207 Object localValue = value; 1208 if (localValue instanceof SetFuture) { 1209 builder.append(", setFuture=["); 1210 appendUserObject(builder, ((SetFuture) localValue).future); 1211 builder.append("]"); 1212 } else { 1213 String pendingDescription; 1214 try { 1215 pendingDescription = Strings.emptyToNull(pendingToString()); 1216 } catch (Exception | StackOverflowError e) { 1217 // Any Exception is either a RuntimeException or sneaky checked exception. 1218 // 1219 // Don't call getMessage or toString() on the exception, in case the exception thrown by the 1220 // subclass is implemented with bugs similar to the subclass. 1221 pendingDescription = "Exception thrown from implementation: " + e.getClass(); 1222 } 1223 if (pendingDescription != null) { 1224 builder.append(", info=[").append(pendingDescription).append("]"); 1225 } 1226 } 1227 1228 // The future may complete while calculating the toString, so we check once more to see if the 1229 // future is done 1230 if (isDone()) { 1231 // Truncate anything that was appended before realizing this future is done 1232 builder.delete(truncateLength, builder.length()); 1233 addDoneString(builder); 1234 } 1235 } 1236 1237 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 1238 private void addDoneString(StringBuilder builder) { 1239 try { 1240 V value = getUninterruptibly(this); 1241 builder.append("SUCCESS, result=["); 1242 appendResultObject(builder, value); 1243 builder.append("]"); 1244 } catch (ExecutionException e) { 1245 builder.append("FAILURE, cause=[").append(e.getCause()).append("]"); 1246 } catch (CancellationException e) { 1247 builder.append("CANCELLED"); // shouldn't be reachable 1248 } catch (Exception e) { // sneaky checked exception 1249 builder.append("UNKNOWN, cause=[").append(e.getClass()).append(" thrown from get()]"); 1250 } 1251 } 1252 1253 /** 1254 * Any object can be the result of a Future, and not every object has a reasonable toString() 1255 * implementation. Using a reconstruction of the default Object.toString() prevents OOMs and stack 1256 * overflows, and helps avoid sensitive data inadvertently ending up in exception messages. 1257 */ 1258 private void appendResultObject(StringBuilder builder, @CheckForNull Object o) { 1259 if (o == null) { 1260 builder.append("null"); 1261 } else if (o == this) { 1262 builder.append("this future"); 1263 } else { 1264 builder 1265 .append(o.getClass().getName()) 1266 .append("@") 1267 .append(Integer.toHexString(System.identityHashCode(o))); 1268 } 1269 } 1270 1271 /** Helper for printing user supplied objects into our toString method. */ 1272 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 1273 private void appendUserObject(StringBuilder builder, @CheckForNull Object o) { 1274 // This is some basic recursion detection for when people create cycles via set/setFuture or 1275 // when deep chains of futures exist resulting in a StackOverflowException. We could detect 1276 // arbitrary cycles using a thread local but this should be a good enough solution (it is also 1277 // what jdk collections do in these cases) 1278 try { 1279 if (o == this) { 1280 builder.append("this future"); 1281 } else { 1282 builder.append(o); 1283 } 1284 } catch (Exception | StackOverflowError e) { 1285 // Any Exception is either a RuntimeException or sneaky checked exception. 1286 // 1287 // Don't call getMessage or toString() on the exception, in case the exception thrown by the 1288 // user object is implemented with bugs similar to the user object. 1289 builder.append("Exception thrown from implementation: ").append(e.getClass()); 1290 } 1291 } 1292 1293 /** 1294 * Submits the given runnable to the given {@link Executor} catching and logging all {@linkplain 1295 * RuntimeException runtime exceptions} thrown by the executor. 1296 */ 1297 @SuppressWarnings("CatchingUnchecked") // sneaky checked exception 1298 private static void executeListener(Runnable runnable, Executor executor) { 1299 try { 1300 executor.execute(runnable); 1301 } catch (Exception e) { // sneaky checked exception 1302 // Log it and keep going -- bad runnable and/or executor. Don't punish the other runnables if 1303 // we're given a bad one. We only catch Exception because we want Errors to propagate up. 1304 log.get() 1305 .log( 1306 Level.SEVERE, 1307 "RuntimeException while executing runnable " 1308 + runnable 1309 + " with executor " 1310 + executor, 1311 e); 1312 } 1313 } 1314 1315 private abstract static class AtomicHelper { 1316 /** Non-volatile write of the thread to the {@link Waiter#thread} field. */ 1317 abstract void putThread(Waiter waiter, Thread newValue); 1318 1319 /** Non-volatile write of the waiter to the {@link Waiter#next} field. */ 1320 abstract void putNext(Waiter waiter, @CheckForNull Waiter newValue); 1321 1322 /** Performs a CAS operation on the {@link #waiters} field. */ 1323 abstract boolean casWaiters( 1324 AbstractFuture<?> future, @CheckForNull Waiter expect, @CheckForNull Waiter update); 1325 1326 /** Performs a CAS operation on the {@link #listeners} field. */ 1327 abstract boolean casListeners( 1328 AbstractFuture<?> future, @CheckForNull Listener expect, Listener update); 1329 1330 /** Performs a GAS operation on the {@link #waiters} field. */ 1331 abstract Waiter gasWaiters(AbstractFuture<?> future, Waiter update); 1332 1333 /** Performs a GAS operation on the {@link #listeners} field. */ 1334 abstract Listener gasListeners(AbstractFuture<?> future, Listener update); 1335 1336 /** Performs a CAS operation on the {@link #value} field. */ 1337 abstract boolean casValue(AbstractFuture<?> future, @CheckForNull Object expect, Object update); 1338 } 1339 1340 /** 1341 * {@link AtomicHelper} based on {@link sun.misc.Unsafe}. 1342 * 1343 * <p>Static initialization of this class will fail if the {@link sun.misc.Unsafe} object cannot 1344 * be accessed. 1345 */ 1346 @SuppressWarnings({"SunApi", "removal"}) // b/345822163 1347 private static final class UnsafeAtomicHelper extends AtomicHelper { 1348 static final Unsafe UNSAFE; 1349 static final long LISTENERS_OFFSET; 1350 static final long WAITERS_OFFSET; 1351 static final long VALUE_OFFSET; 1352 static final long WAITER_THREAD_OFFSET; 1353 static final long WAITER_NEXT_OFFSET; 1354 1355 static { 1356 Unsafe unsafe = null; 1357 try { 1358 unsafe = Unsafe.getUnsafe(); 1359 } catch (SecurityException tryReflectionInstead) { 1360 try { 1361 unsafe = 1362 AccessController.doPrivileged( 1363 new PrivilegedExceptionAction<Unsafe>() { 1364 @Override 1365 public Unsafe run() throws Exception { 1366 Class<Unsafe> k = Unsafe.class; 1367 for (Field f : k.getDeclaredFields()) { 1368 f.setAccessible(true); 1369 Object x = f.get(null); 1370 if (k.isInstance(x)) { 1371 return k.cast(x); 1372 } 1373 } 1374 throw new NoSuchFieldError("the Unsafe"); 1375 } 1376 }); 1377 } catch (PrivilegedActionException e) { 1378 throw new RuntimeException("Could not initialize intrinsics", e.getCause()); 1379 } 1380 } 1381 try { 1382 Class<?> abstractFuture = AbstractFuture.class; 1383 WAITERS_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("waiters")); 1384 LISTENERS_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("listeners")); 1385 VALUE_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("value")); 1386 WAITER_THREAD_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("thread")); 1387 WAITER_NEXT_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("next")); 1388 UNSAFE = unsafe; 1389 } catch (NoSuchFieldException e) { 1390 throw new RuntimeException(e); 1391 } 1392 } 1393 1394 @Override 1395 void putThread(Waiter waiter, Thread newValue) { 1396 UNSAFE.putObject(waiter, WAITER_THREAD_OFFSET, newValue); 1397 } 1398 1399 @Override 1400 void putNext(Waiter waiter, @CheckForNull Waiter newValue) { 1401 UNSAFE.putObject(waiter, WAITER_NEXT_OFFSET, newValue); 1402 } 1403 1404 /** Performs a CAS operation on the {@link #waiters} field. */ 1405 @Override 1406 boolean casWaiters( 1407 AbstractFuture<?> future, @CheckForNull Waiter expect, @CheckForNull Waiter update) { 1408 return UNSAFE.compareAndSwapObject(future, WAITERS_OFFSET, expect, update); 1409 } 1410 1411 /** Performs a CAS operation on the {@link #listeners} field. */ 1412 @Override 1413 boolean casListeners(AbstractFuture<?> future, @CheckForNull Listener expect, Listener update) { 1414 return UNSAFE.compareAndSwapObject(future, LISTENERS_OFFSET, expect, update); 1415 } 1416 1417 /** Performs a GAS operation on the {@link #listeners} field. */ 1418 @Override 1419 Listener gasListeners(AbstractFuture<?> future, Listener update) { 1420 while (true) { 1421 Listener listener = future.listeners; 1422 if (update == listener) { 1423 return listener; 1424 } 1425 if (casListeners(future, listener, update)) { 1426 return listener; 1427 } 1428 } 1429 } 1430 1431 /** Performs a GAS operation on the {@link #waiters} field. */ 1432 @Override 1433 Waiter gasWaiters(AbstractFuture<?> future, Waiter update) { 1434 while (true) { 1435 Waiter waiter = future.waiters; 1436 if (update == waiter) { 1437 return waiter; 1438 } 1439 if (casWaiters(future, waiter, update)) { 1440 return waiter; 1441 } 1442 } 1443 } 1444 1445 /** Performs a CAS operation on the {@link #value} field. */ 1446 @Override 1447 boolean casValue(AbstractFuture<?> future, @CheckForNull Object expect, Object update) { 1448 return UNSAFE.compareAndSwapObject(future, VALUE_OFFSET, expect, update); 1449 } 1450 } 1451 1452 /** {@link AtomicHelper} based on {@link AtomicReferenceFieldUpdater}. */ 1453 private static final class SafeAtomicHelper extends AtomicHelper { 1454 final AtomicReferenceFieldUpdater<Waiter, Thread> waiterThreadUpdater; 1455 final AtomicReferenceFieldUpdater<Waiter, Waiter> waiterNextUpdater; 1456 final AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Waiter> waitersUpdater; 1457 final AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Listener> listenersUpdater; 1458 final AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Object> valueUpdater; 1459 1460 SafeAtomicHelper( 1461 AtomicReferenceFieldUpdater<Waiter, Thread> waiterThreadUpdater, 1462 AtomicReferenceFieldUpdater<Waiter, Waiter> waiterNextUpdater, 1463 AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Waiter> waitersUpdater, 1464 AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Listener> listenersUpdater, 1465 AtomicReferenceFieldUpdater<? super AbstractFuture<?>, Object> valueUpdater) { 1466 this.waiterThreadUpdater = waiterThreadUpdater; 1467 this.waiterNextUpdater = waiterNextUpdater; 1468 this.waitersUpdater = waitersUpdater; 1469 this.listenersUpdater = listenersUpdater; 1470 this.valueUpdater = valueUpdater; 1471 } 1472 1473 @Override 1474 void putThread(Waiter waiter, Thread newValue) { 1475 waiterThreadUpdater.lazySet(waiter, newValue); 1476 } 1477 1478 @Override 1479 void putNext(Waiter waiter, @CheckForNull Waiter newValue) { 1480 waiterNextUpdater.lazySet(waiter, newValue); 1481 } 1482 1483 @Override 1484 boolean casWaiters( 1485 AbstractFuture<?> future, @CheckForNull Waiter expect, @CheckForNull Waiter update) { 1486 return waitersUpdater.compareAndSet(future, expect, update); 1487 } 1488 1489 @Override 1490 boolean casListeners(AbstractFuture<?> future, @CheckForNull Listener expect, Listener update) { 1491 return listenersUpdater.compareAndSet(future, expect, update); 1492 } 1493 1494 /** Performs a GAS operation on the {@link #listeners} field. */ 1495 @Override 1496 Listener gasListeners(AbstractFuture<?> future, Listener update) { 1497 return listenersUpdater.getAndSet(future, update); 1498 } 1499 1500 /** Performs a GAS operation on the {@link #waiters} field. */ 1501 @Override 1502 Waiter gasWaiters(AbstractFuture<?> future, Waiter update) { 1503 return waitersUpdater.getAndSet(future, update); 1504 } 1505 1506 @Override 1507 boolean casValue(AbstractFuture<?> future, @CheckForNull Object expect, Object update) { 1508 return valueUpdater.compareAndSet(future, expect, update); 1509 } 1510 } 1511 1512 /** 1513 * {@link AtomicHelper} based on {@code synchronized} and volatile writes. 1514 * 1515 * <p>This is an implementation of last resort for when certain basic VM features are broken (like 1516 * AtomicReferenceFieldUpdater). 1517 */ 1518 private static final class SynchronizedHelper extends AtomicHelper { 1519 @Override 1520 void putThread(Waiter waiter, Thread newValue) { 1521 waiter.thread = newValue; 1522 } 1523 1524 @Override 1525 void putNext(Waiter waiter, @CheckForNull Waiter newValue) { 1526 waiter.next = newValue; 1527 } 1528 1529 @Override 1530 boolean casWaiters( 1531 AbstractFuture<?> future, @CheckForNull Waiter expect, @CheckForNull Waiter update) { 1532 synchronized (future) { 1533 if (future.waiters == expect) { 1534 future.waiters = update; 1535 return true; 1536 } 1537 return false; 1538 } 1539 } 1540 1541 @Override 1542 boolean casListeners(AbstractFuture<?> future, @CheckForNull Listener expect, Listener update) { 1543 synchronized (future) { 1544 if (future.listeners == expect) { 1545 future.listeners = update; 1546 return true; 1547 } 1548 return false; 1549 } 1550 } 1551 1552 /** Performs a GAS operation on the {@link #listeners} field. */ 1553 @Override 1554 Listener gasListeners(AbstractFuture<?> future, Listener update) { 1555 synchronized (future) { 1556 Listener old = future.listeners; 1557 if (old != update) { 1558 future.listeners = update; 1559 } 1560 return old; 1561 } 1562 } 1563 1564 /** Performs a GAS operation on the {@link #waiters} field. */ 1565 @Override 1566 Waiter gasWaiters(AbstractFuture<?> future, Waiter update) { 1567 synchronized (future) { 1568 Waiter old = future.waiters; 1569 if (old != update) { 1570 future.waiters = update; 1571 } 1572 return old; 1573 } 1574 } 1575 1576 @Override 1577 boolean casValue(AbstractFuture<?> future, @CheckForNull Object expect, Object update) { 1578 synchronized (future) { 1579 if (future.value == expect) { 1580 future.value = update; 1581 return true; 1582 } 1583 return false; 1584 } 1585 } 1586 } 1587 1588 private static CancellationException cancellationExceptionWithCause( 1589 String message, @CheckForNull Throwable cause) { 1590 CancellationException exception = new CancellationException(message); 1591 exception.initCause(cause); 1592 return exception; 1593 } 1594}