001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.util.concurrent;
018
019import static com.google.common.base.Preconditions.checkNotNull;
020import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
021import static java.util.concurrent.atomic.AtomicReferenceFieldUpdater.newUpdater;
022
023import com.google.common.annotations.Beta;
024import com.google.common.annotations.GwtCompatible;
025import com.google.common.base.Throwables;
026import com.google.errorprone.annotations.ForOverride;
027
028import java.security.AccessController;
029import java.security.PrivilegedActionException;
030import java.security.PrivilegedExceptionAction;
031import java.util.concurrent.CancellationException;
032import java.util.concurrent.ExecutionException;
033import java.util.concurrent.Executor;
034import java.util.concurrent.Future;
035import java.util.concurrent.TimeUnit;
036import java.util.concurrent.TimeoutException;
037import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
038import java.util.concurrent.locks.LockSupport;
039import java.util.logging.Level;
040import java.util.logging.Logger;
041
042import javax.annotation.Nullable;
043
044/**
045 * An abstract implementation of {@link ListenableFuture}, intended for advanced users only. More
046 * common ways to create a {@code ListenableFuture} include instantiating a {@link SettableFuture},
047 * submitting a task to a {@link ListeningExecutorService}, and deriving a {@code Future} from an
048 * existing one, typically using methods like {@link Futures#transform(ListenableFuture, Function)
049 * Futures.transform} and {@link Futures#catching(ListenableFuture, Class, Function)
050 * Futures.catching}.
051 *
052 * <p>This class implements all methods in {@code ListenableFuture}. Subclasses should provide a way
053 * to set the result of the computation through the protected methods {@link #set(Object)}, {@link
054 * #setFuture(ListenableFuture)} and {@link #setException(Throwable)}. Subclasses may also override
055 * {@link #interruptTask()}, which will be invoked automatically if a call to {@link
056 * #cancel(boolean) cancel(true)} succeeds in canceling the future. Subclasses should rarely
057 * override other methods.
058 *
059 * @author Sven Mawson
060 * @author Luke Sandberg
061 * @since 1.0
062 */
063@GwtCompatible(emulated = true)
064public abstract class AbstractFuture<V> implements ListenableFuture<V> {
065
066  /**
067   * A less abstract subclass of AbstractFuture.  This can be used to optimize setFuture by ensuring
068   * that {@link #get} calls exactly the implementation of {@link AbstractFuture#get}.
069   */
070  abstract static class TrustedFuture<V> extends AbstractFuture<V> {
071    // N.B. cancel is not overridden to be final, because many future utilities need to override
072    // cancel in order to propagate cancellation to other futures.
073
074    @Override public final V get() throws InterruptedException, ExecutionException {
075      return super.get();
076    }
077
078    @Override public final V get(long timeout, TimeUnit unit)
079        throws InterruptedException, ExecutionException, TimeoutException {
080      return super.get(timeout, unit);
081    }
082
083    @Override public final boolean isDone() {
084      return super.isDone();
085    }
086
087    @Override public final boolean isCancelled() {
088      return super.isCancelled();
089    }
090
091    @Override public final void addListener(Runnable listener, Executor executor) {
092      super.addListener(listener, executor);
093    }
094  }
095
096  // Logger to log exceptions caught when running listeners.
097  private static final Logger log = Logger.getLogger(AbstractFuture.class.getName());
098
099  // A heuristic for timed gets.  If the remaining timeout is less than this, spin instead of
100  // blocking.  This value is what AbstractQueuedSynchronizer uses.
101  private static final long SPIN_THRESHOLD_NANOS = 1000L;
102
103  private static final AtomicHelper ATOMIC_HELPER;
104  private static final AtomicReferenceFieldUpdater<Waiter, Thread> WAITER_THREAD_UPDATER;
105  private static final AtomicReferenceFieldUpdater<Waiter, Waiter> WAITER_NEXT_UPDATER;
106  private static final AtomicReferenceFieldUpdater<AbstractFuture, Waiter> WAITERS_UPDATER;
107  private static final AtomicReferenceFieldUpdater<AbstractFuture, Listener> LISTENERS_UPDATER;
108  private static final AtomicReferenceFieldUpdater<AbstractFuture, Object> VALUE_UPDATER;
109
110  static {
111    AtomicHelper helper = null;
112    try {
113      helper = new UnsafeAtomicHelper();
114    } catch (Throwable e) {
115      // catch absolutely everything and fall through
116    }
117    if (helper == null) {
118      // The access control checks that ARFU does means the caller class has to be AbstractFuture
119      // instead of SafeAtomicHelper, so we annoyingly define these here
120      WAITER_THREAD_UPDATER = newUpdater(Waiter.class, Thread.class, "thread");
121      WAITER_NEXT_UPDATER = newUpdater(Waiter.class, Waiter.class, "next");
122      WAITERS_UPDATER = newUpdater(AbstractFuture.class, Waiter.class, "waiters");
123      LISTENERS_UPDATER = newUpdater(AbstractFuture.class, Listener.class, "listeners");
124      VALUE_UPDATER = newUpdater(AbstractFuture.class, Object.class, "value");
125      helper = new SafeAtomicHelper();
126    } else {
127      WAITER_THREAD_UPDATER = null;
128      WAITER_NEXT_UPDATER = null;
129      WAITERS_UPDATER = null;
130      LISTENERS_UPDATER = null;
131      VALUE_UPDATER = null;
132    }
133    ATOMIC_HELPER = helper;
134
135    // Prevent rare disastrous classloading in first call to LockSupport.park.
136    // See: https://bugs.openjdk.java.net/browse/JDK-8074773
137    Class<?> ensureLoaded = LockSupport.class;
138  }
139
140  /**
141   * Waiter links form a Treiber stack, in the {@link #waiters} field.
142   */
143  private static final class Waiter {
144    static final Waiter TOMBSTONE = new Waiter(false /* ignored param */);
145
146    @Nullable volatile Thread thread;
147    @Nullable volatile Waiter next;
148
149    // Constructor for the TOMBSTONE, avoids use of ATOMIC_HELPER in case this class is loaded
150    // before the ATOMIC_HELPER.  Apparently this is possible on some android platforms.
151    Waiter(@SuppressWarnings("unused") boolean ignored) {}
152
153    Waiter() {
154      // avoid volatile write, write is made visible by subsequent CAS on waiters field
155      ATOMIC_HELPER.putThread(this, Thread.currentThread());
156    }
157
158    // non-volatile write to the next field. Should be made visible by subsequent CAS on waiters
159    // field.
160    void setNext(Waiter next) {
161      ATOMIC_HELPER.putNext(this, next);
162    }
163
164    void unpark() {
165      // This is racy with removeWaiter.  The consequence of the race is that we may spuriously
166      // call unpark even though the thread has already removed itself from the list.  But even if
167      // we did use a CAS, that race would still exist (it would just be ever so slightly smaller).
168      Thread w = thread;
169      if (w != null) {
170        thread = null;
171        LockSupport.unpark(w);
172      }
173    }
174  }
175
176  /**
177   * Marks the given node as 'deleted' (null waiter) and then scans the list to unlink all deleted
178   * nodes.  This is an O(n) operation in the common case (and O(n^2) in the worst), but we are
179   * saved by two things.
180   * <ul>
181   *   <li>This is only called when a waiting thread times out or is interrupted.  Both of which
182   *       should be rare.
183   *   <li>The waiters list should be very short.
184   * </ul>
185   */
186  private void removeWaiter(Waiter node) {
187    node.thread = null;  // mark as 'deleted'
188    restart: while (true) {
189      Waiter pred = null;
190      Waiter curr = waiters;
191      if (curr == Waiter.TOMBSTONE) {
192        return;  // give up if someone is calling complete
193      }
194      Waiter succ;
195      while (curr != null) {
196        succ = curr.next;
197        if (curr.thread != null) {  // we aren't unlinking this node, update pred.
198          pred = curr;
199        } else if (pred != null) { // We are unlinking this node and it has a predecessor.
200          pred.next = succ;
201          if (pred.thread == null) {  // We raced with another node that unlinked pred. Restart.
202            continue restart;
203          }
204        } else if (!ATOMIC_HELPER.casWaiters(this, curr, succ)) {  // We are unlinking head
205          continue restart;  // We raced with an add or complete
206        }
207        curr = succ;
208      }
209      break;
210    }
211  }
212
213  /** Listeners also form a stack through the {@link #listeners} field. */
214  private static final class Listener {
215    static final Listener TOMBSTONE = new Listener(null, null);
216    final Runnable task;
217    final Executor executor;
218
219    // writes to next are made visible by subsequent CAS's on the listeners field
220    @Nullable Listener next;
221
222    Listener(Runnable task, Executor executor) {
223      this.task = task;
224      this.executor = executor;
225    }
226  }
227
228  /** A special value to represent {@code null}. */
229  private static final Object NULL = new Object();
230
231  /** A special value to represent failure, when {@link #setException} is called successfully. */
232  private static final class Failure {
233    static final Failure FALLBACK_INSTANCE = new Failure(
234        new Throwable("Failure occurred while trying to finish a future.") {
235          @Override public synchronized Throwable fillInStackTrace() {
236            return this;  // no stack trace
237          }
238        });
239    final Throwable exception;
240
241    Failure(Throwable exception) {
242      this.exception = checkNotNull(exception);
243    }
244  }
245
246  /** A special value to represent cancellation and the 'wasInterrupted' bit. */
247  private static final class Cancellation {
248    final boolean wasInterrupted;
249    final Throwable cause;
250
251    Cancellation(boolean wasInterrupted, Throwable cause) {
252      this.wasInterrupted = wasInterrupted;
253      this.cause = checkNotNull(cause);
254    }
255  }
256
257  /** A special value that encodes the 'setFuture' state. */
258  private final class SetFuture implements Runnable {
259    final ListenableFuture<? extends V> future;
260
261    SetFuture(ListenableFuture<? extends V> future) {
262      this.future = future;
263    }
264
265    @Override public void run() {
266      if (value != this) {
267        // nothing to do, we must have been cancelled
268        return;
269      }
270      completeWithFuture(future, this);
271    }
272  }
273
274  // TODO(lukes): investigate using the @Contended annotation on these fields when jdk8 is
275  // available.
276  /**
277   * This field encodes the current state of the future.
278   *
279   * <p>The valid values are:
280   * <ul>
281   *   <li>{@code null} initial state, nothing has happened.
282   *   <li>{@link Cancellation} terminal state, {@code cancel} was called.
283   *   <li>{@link Failure} terminal state, {@code setException} was called.
284   *   <li>{@link SetFuture} intermediate state, {@code setFuture} was called.
285   *   <li>{@link #NULL} terminal state, {@code set(null)} was called.
286   *   <li>Any other non-null value, terminal state, {@code set} was called with a non-null
287   *       argument.
288   * </ul>
289   */
290  private volatile Object value;
291
292  /** All listeners. */
293  private volatile Listener listeners;
294
295  /** All waiting threads. */
296  private volatile Waiter waiters;
297
298  /**
299   * Constructor for use by subclasses.
300   */
301  protected AbstractFuture() {}
302
303  /*
304   * Improve the documentation of when InterruptedException is thrown. Our
305   * behavior matches the JDK's, but the JDK's documentation is misleading.
306   */
307
308  // Gets and Timed Gets
309  //
310  // * Be responsive to interruption
311  // * Don't create Waiter nodes if you aren't going to park, this helps reduce contention on the
312  //   waiters field.
313  // * Future completion is defined by when #value becomes non-null/non SetFuture
314  // * Future completion can be observed if the waiters field contains a TOMBSTONE
315
316  // Timed Get
317  // There are a few design constraints to consider
318  // * We want to be responsive to small timeouts, unpark() has non trivial latency overheads (I
319  //   have observed 12 micros on 64 bit linux systems to wake up a parked thread).  So if the
320  //   timeout is small we shouldn't park().  This needs to be traded off with the cpu overhead of
321  //   spinning, so we use SPIN_THRESHOLD_NANOS which is what AbstractQueuedSynchronizer uses for
322  //   similar purposes.
323  // * We want to behave reasonably for timeouts of 0
324  // * We are more responsive to completion than timeouts.  This is because parkNanos depends on
325  //   system scheduling and as such we could either miss our deadline, or unpark() could be delayed
326  //   so that it looks like we timed out even though we didn't.  For comparison FutureTask respects
327  //   completion preferably and AQS is non-deterministic (depends on where in the queue the waiter
328  //   is).  If we wanted to be strict about it, we could store the unpark() time in the Waiter
329  //   node and we could use that to make a decision about whether or not we timed out prior to
330  //   being unparked.
331
332  /**
333   * {@inheritDoc}
334   *
335   * <p>The default {@link AbstractFuture} implementation throws {@code
336   * InterruptedException} if the current thread is interrupted before or during
337   * the call, even if the value is already available.
338   *
339   * @throws InterruptedException if the current thread was interrupted before
340   *     or during the call (optional but recommended).
341   * @throws CancellationException {@inheritDoc}
342   */
343  @Override
344  public V get(long timeout, TimeUnit unit)
345      throws InterruptedException, TimeoutException, ExecutionException {
346    // NOTE: if timeout < 0, remainingNanos will be < 0 and we will fall into the while(true) loop
347    // at the bottom and throw a timeoutexception.
348    long remainingNanos = unit.toNanos(timeout); // we rely on the implicit null check on unit.
349    if (Thread.interrupted()) {
350      throw new InterruptedException();
351    }
352    Object localValue = value;
353    if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
354      return getDoneValue(localValue);
355    }
356    // we delay calling nanoTime until we know we will need to either park or spin
357    final long endNanos = remainingNanos > 0 ? System.nanoTime() + remainingNanos : 0;
358    long_wait_loop: if (remainingNanos >= SPIN_THRESHOLD_NANOS) {
359      Waiter oldHead = waiters;
360      if (oldHead != Waiter.TOMBSTONE) {
361        Waiter node = new Waiter();
362        do {
363          node.setNext(oldHead);
364          if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) {
365            while (true) {
366              LockSupport.parkNanos(this, remainingNanos);
367              // Check interruption first, if we woke up due to interruption we need to honor that.
368              if (Thread.interrupted()) {
369                removeWaiter(node);
370                throw new InterruptedException();
371              }
372
373              // Otherwise re-read and check doneness.  If we loop then it must have been a spurious
374              // wakeup
375              localValue = value;
376              if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
377                return getDoneValue(localValue);
378              }
379
380              // timed out?
381              remainingNanos = endNanos - System.nanoTime();
382              if (remainingNanos < SPIN_THRESHOLD_NANOS) {
383                // Remove the waiter, one way or another we are done parking this thread.
384                removeWaiter(node);
385                break long_wait_loop;  // jump down to the busy wait loop
386              }
387            }
388          }
389          oldHead = waiters;  // re-read and loop.
390        } while (oldHead != Waiter.TOMBSTONE);
391      }
392      // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a
393      // waiter.
394      return getDoneValue(value);
395    }
396    // If we get here then we have remainingNanos < SPIN_THRESHOLD_NANOS and there is no node on the
397    // waiters list
398    while (remainingNanos > 0) {
399      localValue = value;
400      if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
401        return getDoneValue(localValue);
402      }
403      if (Thread.interrupted()) {
404        throw new InterruptedException();
405      }
406      remainingNanos = endNanos - System.nanoTime();
407    }
408    throw new TimeoutException();
409  }
410
411  /*
412   * Improve the documentation of when InterruptedException is thrown. Our
413   * behavior matches the JDK's, but the JDK's documentation is misleading.
414   */
415  /**
416   * {@inheritDoc}
417   *
418   * <p>The default {@link AbstractFuture} implementation throws {@code
419   * InterruptedException} if the current thread is interrupted before or during
420   * the call, even if the value is already available.
421   *
422   * @throws InterruptedException if the current thread was interrupted before
423   *     or during the call (optional but recommended).
424   * @throws CancellationException {@inheritDoc}
425   */
426  @Override public V get() throws InterruptedException, ExecutionException {
427    if (Thread.interrupted()) {
428      throw new InterruptedException();
429    }
430    Object localValue = value;
431    if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
432      return getDoneValue(localValue);
433    }
434    Waiter oldHead = waiters;
435    if (oldHead != Waiter.TOMBSTONE) {
436      Waiter node = new Waiter();
437      do {
438        node.setNext(oldHead);
439        if (ATOMIC_HELPER.casWaiters(this, oldHead, node)) {
440          // we are on the stack, now wait for completion.
441          while (true) {
442            LockSupport.park(this);
443            // Check interruption first, if we woke up due to interruption we need to honor that.
444            if (Thread.interrupted()) {
445              removeWaiter(node);
446              throw new InterruptedException();
447            }
448            // Otherwise re-read and check doneness.  If we loop then it must have been a spurious
449            // wakeup
450            localValue = value;
451            if (localValue != null & !(localValue instanceof AbstractFuture.SetFuture)) {
452              return getDoneValue(localValue);
453            }
454          }
455        }
456        oldHead = waiters;  // re-read and loop.
457      } while (oldHead != Waiter.TOMBSTONE);
458    }
459    // re-read value, if we get here then we must have observed a TOMBSTONE while trying to add a
460    // waiter.
461    return getDoneValue(value);
462  }
463
464  /**
465   * Unboxes {@code obj}.  Assumes that obj is not {@code null} or a {@link SetFuture}.
466   */
467  private V getDoneValue(Object obj) throws ExecutionException {
468    // While this seems like it might be too branch-y, simple benchmarking proves it to be
469    // unmeasurable (comparing done AbstractFutures with immediateFuture)
470    if (obj instanceof Cancellation) {
471      throw cancellationExceptionWithCause("Task was cancelled.", ((Cancellation) obj).cause);
472    } else if (obj instanceof Failure) {
473      throw new ExecutionException(((Failure) obj).exception);
474    } else if (obj == NULL) {
475      return null;
476    } else {
477      @SuppressWarnings("unchecked")  // this is the only other option
478      V asV = (V) obj;
479      return asV;
480    }
481  }
482
483  @Override
484  public boolean isDone() {
485    final Object localValue = value;
486    return localValue != null & !(localValue instanceof AbstractFuture.SetFuture);
487  }
488
489  @Override
490  public boolean isCancelled() {
491    final Object localValue = value;
492    return localValue instanceof Cancellation;
493  }
494
495  /**
496   * {@inheritDoc}
497   *
498   * <p>If a cancellation attempt succeeds on a {@code Future} that had previously been {@linkplain
499   * #setFuture set asynchronously}, then the cancellation will also be propagated to the delegate
500   * {@code Future} that was supplied in the {@code setFuture} call.
501   */
502  @Override
503  public boolean cancel(boolean mayInterruptIfRunning) {
504    Object localValue = value;
505    if (localValue == null | localValue instanceof AbstractFuture.SetFuture) {
506      // Try to delay allocating the exception.  At this point we may still lose the CAS, but it is
507      // certainly less likely.
508      // TODO(lukes): this exception actually makes cancellation significantly more expensive :(
509      // I wonder if we should consider removing it or providing a mechanism to not do it.
510      Object valueToSet = new Cancellation(mayInterruptIfRunning, newCancellationCause());
511      do {
512        if (ATOMIC_HELPER.casValue(this, localValue, valueToSet)) {
513          // We call interuptTask before calling complete(), first which is consistent with
514          // FutureTask
515          if (mayInterruptIfRunning) {
516            interruptTask();
517          }
518          complete();
519          if (localValue instanceof AbstractFuture.SetFuture) {
520            // propagate cancellation to the future set in setfuture, this is racy, and we don't
521            // care if we are successful or not.
522            ((AbstractFuture<?>.SetFuture) localValue).future.cancel(mayInterruptIfRunning);
523          }
524          return true;
525        }
526        // obj changed, reread
527        localValue = value;
528        // obj cannot be null at this point, because value can only change from null to non-null. So
529        // if value changed (and it did since we lost the CAS), then it cannot be null.
530      } while (localValue instanceof AbstractFuture.SetFuture);
531    }
532    return false;
533  }
534
535  /**
536   * Returns an exception to be used as the cause of the CancellationException thrown by
537   * {@link #get}.
538   *
539   * <p>Note: this method may be called speculatively.  There is no guarantee that the future will
540   * be cancelled if this method is called.
541   *
542   * @since 19.0
543   */
544  @Beta
545  protected Throwable newCancellationCause() {
546    return new CancellationException("Future.cancel() was called.");
547  }
548
549  /**
550   * Subclasses can override this method to implement interruption of the
551   * future's computation. The method is invoked automatically by a successful
552   * call to {@link #cancel(boolean) cancel(true)}.
553   *
554   * <p>The default implementation does nothing.
555   *
556   * @since 10.0
557   */
558  protected void interruptTask() {
559  }
560
561  /**
562   * Returns true if this future was cancelled with {@code
563   * mayInterruptIfRunning} set to {@code true}.
564   *
565   * @since 14.0
566   */
567  protected final boolean wasInterrupted() {
568    final Object localValue = value;
569    return (localValue instanceof Cancellation) && ((Cancellation) localValue).wasInterrupted;
570  }
571
572  /**
573   * {@inheritDoc}
574   *
575   * @since 10.0
576   */
577  @Override
578  public void addListener(Runnable listener, Executor executor) {
579    checkNotNull(listener, "Runnable was null.");
580    checkNotNull(executor, "Executor was null.");
581    Listener oldHead = listeners;
582    if (oldHead != Listener.TOMBSTONE) {
583      Listener newNode = new Listener(listener, executor);
584      do {
585        newNode.next = oldHead;
586        if (ATOMIC_HELPER.casListeners(this, oldHead, newNode)) {
587          return;
588        }
589        oldHead = listeners;  // re-read
590      } while (oldHead != Listener.TOMBSTONE);
591    }
592    // If we get here then the Listener TOMBSTONE was set, which means the future is done, call
593    // the listener.
594    executeListener(listener, executor);
595  }
596
597  /**
598   * Sets the result of this {@code Future} unless this {@code Future} has already been cancelled or
599   * set (including {@linkplain #setFuture set asynchronously}). When a call to this method returns,
600   * the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b> the call was
601   * accepted (in which case it returns {@code true}). If it returns {@code false}, the {@code
602   * Future} may have previously been set asynchronously, in which case its result may not be known
603   * yet. That result, though not yet known, cannot by overridden by a call to a {@code set*}
604   * method, only by a call to {@link #cancel}.
605   *
606   * @param value the value to be used as the result
607   * @return true if the attempt was accepted, completing the {@code Future}
608   */
609  protected boolean set(@Nullable V value) {
610    Object valueToSet = value == null ? NULL : value;
611    if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
612      complete();
613      return true;
614    }
615    return false;
616  }
617
618  /**
619   * Sets the failed result of this {@code Future} unless this {@code Future} has already been
620   * cancelled or set (including {@linkplain #setFuture set asynchronously}). When a call to this
621   * method returns, the {@code Future} is guaranteed to be {@linkplain #isDone done} <b>only if</b>
622   * the call was accepted (in which case it returns {@code true}). If it returns {@code false}, the
623   * {@code Future} may have previously been set asynchronously, in which case its result may not be
624   * known yet. That result, though not yet known, cannot by overridden by a call to a {@code set*}
625   * method, only by a call to {@link #cancel}.
626   *
627   * @param throwable the exception to be used as the failed result
628   * @return true if the attempt was accepted, completing the {@code Future}
629   */
630  protected boolean setException(Throwable throwable) {
631    Object valueToSet = new Failure(checkNotNull(throwable));
632    if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
633      complete();
634      return true;
635    }
636    return false;
637  }
638
639  /**
640   * Sets the result of this {@code Future} to match the supplied input {@code Future} once the
641   * supplied {@code Future} is done, unless this {@code Future} has already been cancelled or set
642   * (including "set asynchronously," defined below).
643   *
644   * <p>If the supplied future is {@linkplain #isDone done} when this method is called and the call
645   * is accepted, then this future is guaranteed to have been completed with the supplied future by
646   * the time this method returns. If the supplied future is not done and the call is accepted, then
647   * the future will be <i>set asynchronously</i>. Note that such a result, though not yet known,
648   * cannot by overridden by a call to a {@code set*} method, only by a call to {@link #cancel}.
649   *
650   * <p>If the call {@code setFuture(delegate)} is accepted and this {@code Future} is later
651   * cancelled, cancellation will be propagated to {@code delegate}. Additionally, any call to
652   * {@code setFuture} after any cancellation will propagate cancellation to the supplied {@code
653   * Future}.
654   *
655   * @param future the future to delegate to
656   * @return true if the attempt was accepted, indicating that the {@code Future} was not previously
657   *     cancelled or set.
658   * @since 19.0
659   */
660  @Beta protected boolean setFuture(ListenableFuture<? extends V> future) {
661    checkNotNull(future);
662    Object localValue = value;
663    if (localValue == null) {
664      if (future.isDone()) {
665        return completeWithFuture(future, null);
666      }
667      SetFuture valueToSet = new SetFuture(future);
668      if (ATOMIC_HELPER.casValue(this, null, valueToSet)) {
669        // the listener is responsible for calling completeWithFuture, directExecutor is appropriate
670        // since all we are doing is unpacking a completed future which should be fast.
671        try {
672          future.addListener(valueToSet, directExecutor());
673        } catch (Throwable t) {
674          // addListener has thrown an exception!  SetFuture.run can't throw any exceptions so this
675          // must have been caused by addListener itself.  The most likely explanation is a
676          // misconfigured mock.  Try to switch to Failure.
677          Failure failure;
678          try {
679            failure = new Failure(t);
680          } catch (Throwable oomMostLikely) {
681            failure = Failure.FALLBACK_INSTANCE;
682          }
683          // Note: The only way this CAS could fail is if cancel() has raced with us. That is ok.
684          ATOMIC_HELPER.casValue(this, valueToSet, failure);
685        }
686        return true;
687      }
688      localValue = value;  // we lost the cas, fall through and maybe cancel
689    }
690    // The future has already been set to something.  If it is cancellation we should cancel the
691    // incoming future.
692    if (localValue instanceof Cancellation) {
693      // we don't care if it fails, this is best-effort.
694      future.cancel(((Cancellation) localValue).wasInterrupted);
695    }
696    return false;
697  }
698
699  /**
700   * Called when a future passed via setFuture has completed.
701   *
702   * @param future the done future to complete this future with.
703   * @param expected the expected value of the {@link #value} field.
704   */
705  private boolean completeWithFuture(ListenableFuture<? extends V> future, Object expected) {
706    Object valueToSet;
707    if (future instanceof TrustedFuture) {
708      // Break encapsulation for TrustedFuture instances since we know that subclasses cannot
709      // override .get() (since it is final) and therefore this is equivalent to calling .get()
710      // and unpacking the exceptions like we do below (just much faster because it is a single
711      // field read instead of a read, several branches and possibly creating exceptions).
712      valueToSet = ((AbstractFuture<?>) future).value;
713    } else {
714      // Otherwise calculate valueToSet by calling .get()
715      try {
716        V v = Uninterruptibles.getUninterruptibly(future);
717        valueToSet = v == null ? NULL : v;
718      } catch (ExecutionException exception) {
719        valueToSet = new Failure(exception.getCause());
720      } catch (CancellationException cancellation) {
721        valueToSet = new Cancellation(false, cancellation);
722      } catch (Throwable t) {
723        valueToSet = new Failure(t);
724      }
725    }
726    // The only way this can fail is if we raced with another thread calling cancel(). If we lost
727    // that race then there is nothing to do.
728    if (ATOMIC_HELPER.casValue(AbstractFuture.this, expected, valueToSet)) {
729      complete();
730      return true;
731    }
732    return false;
733  }
734
735  /** Unblocks all threads and runs all listeners. */
736  private void complete() {
737    for (Waiter currentWaiter = clearWaiters();
738        currentWaiter != null;
739        currentWaiter = currentWaiter.next) {
740      currentWaiter.unpark();
741    }
742    // We need to reverse the list to handle buggy listeners that depend on ordering.
743    Listener currentListener = clearListeners();
744    Listener reversedList = null;
745    while (currentListener != null) {
746      Listener tmp = currentListener;
747      currentListener = currentListener.next;
748      tmp.next = reversedList;
749      reversedList = tmp;
750    }
751    for (; reversedList != null; reversedList = reversedList.next) {
752      executeListener(reversedList.task, reversedList.executor);
753    }
754    // We call this after the listeners on the theory that done() will only be used for 'cleanup'
755    // oriented tasks (e.g. clearing fields) and so can wait behind listeners which may be executing
756    // more important work.  A counter argument would be that done() is trusted code and therefore
757    // it would be safe to run before potentially slow or poorly behaved listeners.  Reevaluate this
758    // once we have more examples of done() implementations.
759    done();
760  }
761
762  /**
763   * Callback method that is called immediately after the future is completed.
764   *
765   * <p>This is called exactly once, after all listeners have executed.  By default it does nothing.
766   */
767  // TODO(cpovirk): @ForOverride if https://github.com/google/error-prone/issues/342 permits
768  void done() {}
769
770  /**
771   * Returns the exception that this {@code Future} completed with. This includes completion through
772   * a call to {@link setException} or {@link setFuture}{@code (failedFuture)} but not cancellation.
773   *
774   * @throws RuntimeException if the {@code Future} has not failed
775   */
776  final Throwable trustedGetException() {
777    return ((Failure) value).exception;
778  }
779
780  /**
781   * If this future has been cancelled (and possibly interrupted), cancels (and possibly interrupts)
782   * the given future (if available).
783   *
784   * <p>This method should be used only when this future is completed. It is designed to be called
785   * from {@code done}.
786   */
787  final void maybePropagateCancellation(@Nullable Future<?> related) {
788    if (related != null & isCancelled()) {
789      related.cancel(wasInterrupted());
790    }
791  }
792
793  /** Clears the {@link #waiters} list and returns the most recently added value. */
794  private Waiter clearWaiters() {
795    Waiter head;
796    do {
797      head = waiters;
798    } while (!ATOMIC_HELPER.casWaiters(this, head, Waiter.TOMBSTONE));
799    return head;
800  }
801
802  /** Clears the {@link #listeners} list and returns the most recently added value. */
803  private Listener clearListeners() {
804    Listener head;
805    do {
806      head = listeners;
807    } while (!ATOMIC_HELPER.casListeners(this, head, Listener.TOMBSTONE));
808    return head;
809  }
810
811  /**
812   * Submits the given runnable to the given {@link Executor} catching and logging all
813   * {@linkplain RuntimeException runtime exceptions} thrown by the executor.
814   */
815  private static void executeListener(Runnable runnable, Executor executor) {
816    try {
817      executor.execute(runnable);
818    } catch (RuntimeException e) {
819      // Log it and keep going, bad runnable and/or executor.  Don't
820      // punish the other runnables if we're given a bad one.  We only
821      // catch RuntimeException because we want Errors to propagate up.
822      log.log(Level.SEVERE, "RuntimeException while executing runnable "
823          + runnable + " with executor " + executor, e);
824    }
825  }
826
827  static final CancellationException cancellationExceptionWithCause(
828      @Nullable String message, @Nullable Throwable cause) {
829    CancellationException exception = new CancellationException(message);
830    exception.initCause(cause);
831    return exception;
832  }
833
834  private abstract static class AtomicHelper {
835    /** Non volatile write of the thread to the {@link Waiter#thread} field. */
836    abstract void putThread(Waiter waiter, Thread thread);
837
838    /** Non volatile write of the waiter to the {@link Waiter#next} field. */
839    abstract void putNext(Waiter waiter, Waiter next);
840
841    /** Performs a CAS operation on the {@link #waiters} field. */
842    abstract boolean casWaiters(AbstractFuture future, Waiter curr, Waiter next);
843
844    /** Performs a CAS operation on the {@link #listeners} field. */
845    abstract boolean casListeners(AbstractFuture future, Listener curr, Listener next);
846
847    /** Performs a CAS operation on the {@link #value} field. */
848    abstract boolean casValue(AbstractFuture future, Object expected, Object v);
849  }
850
851  /**
852   * {@link AtomicHelper} based on {@link sun.misc.Unsafe}.
853   *
854   * <p>Static initialization of this class will fail if the {@link sun.misc.Unsafe} object cannot
855   * be accessed.
856   */
857  private static final class UnsafeAtomicHelper extends AtomicHelper {
858    static final sun.misc.Unsafe UNSAFE;
859    static final long LISTENERS_OFFSET;
860    static final long WAITERS_OFFSET;
861    static final long VALUE_OFFSET;
862    static final long WAITER_THREAD_OFFSET;
863    static final long WAITER_NEXT_OFFSET;
864
865    static {
866      sun.misc.Unsafe unsafe = null;
867      try {
868        unsafe = sun.misc.Unsafe.getUnsafe();
869      } catch (SecurityException tryReflectionInstead) {
870        try {
871          unsafe = AccessController.doPrivileged(
872              new PrivilegedExceptionAction<sun.misc.Unsafe>() {
873                @Override public sun.misc.Unsafe run() throws Exception {
874                  Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
875                  for (java.lang.reflect.Field f : k.getDeclaredFields()) {
876                    f.setAccessible(true);
877                    Object x = f.get(null);
878                    if (k.isInstance(x)) {
879                      return k.cast(x);
880                    }
881                  }
882                  throw new NoSuchFieldError("the Unsafe");
883                }
884              });
885        } catch (PrivilegedActionException e) {
886          throw new RuntimeException("Could not initialize intrinsics", e.getCause());
887        }
888      }
889      try {
890        Class<?> abstractFuture = AbstractFuture.class;
891        WAITERS_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("waiters"));
892        LISTENERS_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("listeners"));
893        VALUE_OFFSET = unsafe.objectFieldOffset(abstractFuture.getDeclaredField("value"));
894        WAITER_THREAD_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("thread"));
895        WAITER_NEXT_OFFSET = unsafe.objectFieldOffset(Waiter.class.getDeclaredField("next"));
896        UNSAFE = unsafe;
897      } catch (Exception e) {
898        throw Throwables.propagate(e);
899      }
900    }
901
902    @Override void putThread(Waiter waiter, Thread thread) {
903      UNSAFE.putObject(waiter, WAITER_THREAD_OFFSET, thread);
904    }
905
906    @Override void putNext(Waiter waiter, Waiter next) {
907      UNSAFE.putObject(waiter, WAITER_NEXT_OFFSET, next);
908    }
909
910    /** Performs a CAS operation on the {@link #waiters} field. */
911    @Override boolean casWaiters(AbstractFuture future, Waiter curr, Waiter next) {
912      return UNSAFE.compareAndSwapObject(future, WAITERS_OFFSET, curr, next);
913    }
914
915    /** Performs a CAS operation on the {@link #listeners} field. */
916    @Override boolean casListeners(AbstractFuture future, Listener curr, Listener next) {
917      return UNSAFE.compareAndSwapObject(future, LISTENERS_OFFSET, curr, next);
918    }
919
920    /** Performs a CAS operation on the {@link #value} field. */
921    @Override boolean casValue(AbstractFuture future, Object expected, Object v) {
922      return UNSAFE.compareAndSwapObject(future, VALUE_OFFSET, expected, v);
923    }
924  }
925
926  /** {@link AtomicHelper} based on {@link AtomicReferenceFieldUpdater}. */
927  private static final class SafeAtomicHelper extends AtomicHelper {
928    @Override void putThread(Waiter waiter, Thread thread) {
929      WAITER_THREAD_UPDATER.lazySet(waiter, thread);
930    }
931
932    @Override void putNext(Waiter waiter, Waiter next) {
933      WAITER_NEXT_UPDATER.lazySet(waiter, next);
934    }
935
936    @Override boolean casWaiters(AbstractFuture future, Waiter curr, Waiter next) {
937      return WAITERS_UPDATER.compareAndSet(future, curr, next);
938    }
939
940    @Override boolean casListeners(AbstractFuture future, Listener curr, Listener next) {
941      return LISTENERS_UPDATER.compareAndSet(future, curr, next);
942    }
943
944    @Override boolean casValue(AbstractFuture future, Object expected, Object v) {
945      return VALUE_UPDATER.compareAndSet(future, expected, v);
946    }
947  }
948}