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    
017    package com.google.common.util.concurrent;
018    
019    import static com.google.common.base.Preconditions.checkNotNull;
020    
021    import java.util.concurrent.CancellationException;
022    import java.util.concurrent.ExecutionException;
023    import java.util.concurrent.Executor;
024    import java.util.concurrent.TimeUnit;
025    import java.util.concurrent.TimeoutException;
026    import java.util.concurrent.locks.AbstractQueuedSynchronizer;
027    
028    import javax.annotation.Nullable;
029    
030    /**
031     * An abstract implementation of the {@link ListenableFuture} interface. This
032     * class is preferable to {@link java.util.concurrent.FutureTask} for two
033     * reasons: It implements {@code ListenableFuture}, and it does not implement
034     * {@code Runnable}. (If you want a {@code Runnable} implementation of {@code
035     * ListenableFuture}, create a {@link ListenableFutureTask}, or submit your
036     * tasks to a {@link ListeningExecutorService}.)
037     *
038     * <p>This class implements all methods in {@code ListenableFuture}.
039     * Subclasses should provide a way to set the result of the computation through
040     * the protected methods {@link #set(Object)} and
041     * {@link #setException(Throwable)}. Subclasses may also override {@link
042     * #interruptTask()}, which will be invoked automatically if a call to {@link
043     * #cancel(boolean) cancel(true)} succeeds in canceling the future.
044     *
045     * <p>{@code AbstractFuture} uses an {@link AbstractQueuedSynchronizer} to deal
046     * with concurrency issues and guarantee thread safety.
047     *
048     * <p>The state changing methods all return a boolean indicating success or
049     * failure in changing the future's state.  Valid states are running,
050     * completed, failed, or cancelled.
051     *
052     * <p>This class uses an {@link ExecutionList} to guarantee that all registered
053     * listeners will be executed, either when the future finishes or, for listeners
054     * that are added after the future completes, immediately.
055     * {@code Runnable}-{@code Executor} pairs are stored in the execution list but
056     * are not necessarily executed in the order in which they were added.  (If a
057     * listener is added after the Future is complete, it will be executed
058     * immediately, even if earlier listeners have not been executed. Additionally,
059     * executors need not guarantee FIFO execution, or different listeners may run
060     * in different executors.)
061     *
062     * @author Sven Mawson
063     * @since 1.0
064     */
065    public abstract class AbstractFuture<V> implements ListenableFuture<V> {
066    
067      /** Synchronization control for AbstractFutures. */
068      private final Sync<V> sync = new Sync<V>();
069    
070      // The execution list to hold our executors.
071      private final ExecutionList executionList = new ExecutionList();
072    
073      /**
074       * Constructor for use by subclasses.
075       */
076      protected AbstractFuture() {}
077    
078      /*
079       * Improve the documentation of when InterruptedException is thrown. Our
080       * behavior matches the JDK's, but the JDK's documentation is misleading.
081       */
082      /**
083       * {@inheritDoc}
084       *
085       * <p>The default {@link AbstractFuture} implementation throws {@code
086       * InterruptedException} if the current thread is interrupted before or during
087       * the call, even if the value is already available.
088       *
089       * @throws InterruptedException if the current thread was interrupted before
090       *     or during the call (optional but recommended).
091       * @throws CancellationException {@inheritDoc}
092       */
093      public V get(long timeout, TimeUnit unit) throws InterruptedException,
094          TimeoutException, ExecutionException {
095        return sync.get(unit.toNanos(timeout));
096      }
097    
098      /*
099       * Improve the documentation of when InterruptedException is thrown. Our
100       * behavior matches the JDK's, but the JDK's documentation is misleading.
101       */
102      /**
103       * {@inheritDoc}
104       *
105       * <p>The default {@link AbstractFuture} implementation throws {@code
106       * InterruptedException} if the current thread is interrupted before or during
107       * the call, even if the value is already available.
108       *
109       * @throws InterruptedException if the current thread was interrupted before
110       *     or during the call (optional but recommended).
111       * @throws CancellationException {@inheritDoc}
112       */
113      public V get() throws InterruptedException, ExecutionException {
114        return sync.get();
115      }
116    
117      public boolean isDone() {
118        return sync.isDone();
119      }
120    
121      public boolean isCancelled() {
122        return sync.isCancelled();
123      }
124    
125      public boolean cancel(boolean mayInterruptIfRunning) {
126        if (!sync.cancel()) {
127          return false;
128        }
129        executionList.execute();
130        if (mayInterruptIfRunning) {
131          interruptTask();
132        }
133        return true;
134      }
135    
136      /**
137       * Subclasses can override this method to implement interruption of the
138       * future's computation. The method is invoked automatically by a successful
139       * call to {@link #cancel(boolean) cancel(true)}.
140       *
141       * <p>The default implementation does nothing.
142       *
143       * @since 10.0
144       */
145      protected void interruptTask() {
146      }
147    
148      /**
149       * {@inheritDoc}
150       *
151       * @since 10.0
152       */
153      public void addListener(Runnable listener, Executor exec) {
154        executionList.add(listener, exec);
155      }
156    
157      /**
158       * Subclasses should invoke this method to set the result of the computation
159       * to {@code value}.  This will set the state of the future to
160       * {@link AbstractFuture.Sync#COMPLETED} and invoke the listeners if the
161       * state was successfully changed.
162       *
163       * @param value the value that was the result of the task.
164       * @return true if the state was successfully changed.
165       */
166      protected boolean set(@Nullable V value) {
167        boolean result = sync.set(value);
168        if (result) {
169          executionList.execute();
170        }
171        return result;
172      }
173    
174      /**
175       * Subclasses should invoke this method to set the result of the computation
176       * to an error, {@code throwable}.  This will set the state of the future to
177       * {@link AbstractFuture.Sync#COMPLETED} and invoke the listeners if the
178       * state was successfully changed.
179       *
180       * @param throwable the exception that the task failed with.
181       * @return true if the state was successfully changed.
182       * @throws Error if the throwable was an {@link Error}.
183       */
184      protected boolean setException(Throwable throwable) {
185        boolean result = sync.setException(checkNotNull(throwable));
186        if (result) {
187          executionList.execute();
188        }
189    
190        // If it's an Error, we want to make sure it reaches the top of the
191        // call stack, so we rethrow it.
192        if (throwable instanceof Error) {
193          throw (Error) throwable;
194        }
195        return result;
196      }
197    
198      /**
199       * <p>Following the contract of {@link AbstractQueuedSynchronizer} we create a
200       * private subclass to hold the synchronizer.  This synchronizer is used to
201       * implement the blocking and waiting calls as well as to handle state changes
202       * in a thread-safe manner.  The current state of the future is held in the
203       * Sync state, and the lock is released whenever the state changes to either
204       * {@link #COMPLETED} or {@link #CANCELLED}.
205       *
206       * <p>To avoid races between threads doing release and acquire, we transition
207       * to the final state in two steps.  One thread will successfully CAS from
208       * RUNNING to COMPLETING, that thread will then set the result of the
209       * computation, and only then transition to COMPLETED or CANCELLED.
210       *
211       * <p>We don't use the integer argument passed between acquire methods so we
212       * pass around a -1 everywhere.
213       */
214      static final class Sync<V> extends AbstractQueuedSynchronizer {
215    
216        private static final long serialVersionUID = 0L;
217    
218        /* Valid states. */
219        static final int RUNNING = 0;
220        static final int COMPLETING = 1;
221        static final int COMPLETED = 2;
222        static final int CANCELLED = 4;
223    
224        private V value;
225        private Throwable exception;
226    
227        /*
228         * Acquisition succeeds if the future is done, otherwise it fails.
229         */
230        
231        @Override
232        protected int tryAcquireShared(int ignored) {
233          if (isDone()) {
234            return 1;
235          }
236          return -1;
237        }
238    
239        /*
240         * We always allow a release to go through, this means the state has been
241         * successfully changed and the result is available.
242         */
243        
244        @Override
245        protected boolean tryReleaseShared(int finalState) {
246          setState(finalState);
247          return true;
248        }
249    
250        /**
251         * Blocks until the task is complete or the timeout expires.  Throws a
252         * {@link TimeoutException} if the timer expires, otherwise behaves like
253         * {@link #get()}.
254         */
255        V get(long nanos) throws TimeoutException, CancellationException,
256            ExecutionException, InterruptedException {
257    
258          // Attempt to acquire the shared lock with a timeout.
259          if (!tryAcquireSharedNanos(-1, nanos)) {
260            throw new TimeoutException("Timeout waiting for task.");
261          }
262    
263          return getValue();
264        }
265    
266        /**
267         * Blocks until {@link #complete(Object, Throwable, int)} has been
268         * successfully called.  Throws a {@link CancellationException} if the task
269         * was cancelled, or a {@link ExecutionException} if the task completed with
270         * an error.
271         */
272        V get() throws CancellationException, ExecutionException,
273            InterruptedException {
274    
275          // Acquire the shared lock allowing interruption.
276          acquireSharedInterruptibly(-1);
277          return getValue();
278        }
279    
280        /**
281         * Implementation of the actual value retrieval.  Will return the value
282         * on success, an exception on failure, a cancellation on cancellation, or
283         * an illegal state if the synchronizer is in an invalid state.
284         */
285        private V getValue() throws CancellationException, ExecutionException {
286          int state = getState();
287          switch (state) {
288            case COMPLETED:
289              if (exception != null) {
290                throw new ExecutionException(exception);
291              } else {
292                return value;
293              }
294    
295            case CANCELLED:
296              throw new CancellationException("Task was cancelled.");
297    
298            default:
299              throw new IllegalStateException(
300                  "Error, synchronizer in invalid state: " + state);
301          }
302        }
303    
304        /**
305         * Checks if the state is {@link #COMPLETED} or {@link #CANCELLED}.
306         */
307        boolean isDone() {
308          return (getState() & (COMPLETED | CANCELLED)) != 0;
309        }
310    
311        /**
312         * Checks if the state is {@link #CANCELLED}.
313         */
314        boolean isCancelled() {
315          return getState() == CANCELLED;
316        }
317    
318        /**
319         * Transition to the COMPLETED state and set the value.
320         */
321        boolean set(@Nullable V v) {
322          return complete(v, null, COMPLETED);
323        }
324    
325        /**
326         * Transition to the COMPLETED state and set the exception.
327         */
328        boolean setException(Throwable t) {
329          return complete(null, t, COMPLETED);
330        }
331    
332        /**
333         * Transition to the CANCELLED state.
334         */
335        boolean cancel() {
336          return complete(null, null, CANCELLED);
337        }
338    
339        /**
340         * Implementation of completing a task.  Either {@code v} or {@code t} will
341         * be set but not both.  The {@code finalState} is the state to change to
342         * from {@link #RUNNING}.  If the state is not in the RUNNING state we
343         * return {@code false} after waiting for the state to be set to a valid
344         * final state ({@link #COMPLETED} or {@link #CANCELLED}).
345         *
346         * @param v the value to set as the result of the computation.
347         * @param t the exception to set as the result of the computation.
348         * @param finalState the state to transition to.
349         */
350        private boolean complete(@Nullable V v, @Nullable Throwable t,
351            int finalState) {
352          boolean doCompletion = compareAndSetState(RUNNING, COMPLETING);
353          if (doCompletion) {
354            // If this thread successfully transitioned to COMPLETING, set the value
355            // and exception and then release to the final state.
356            this.value = v;
357            this.exception = t;
358            releaseShared(finalState);
359          } else if (getState() == COMPLETING) {
360            // If some other thread is currently completing the future, block until
361            // they are done so we can guarantee completion.
362            acquireShared(-1);
363          }
364          return doCompletion;
365        }
366      }
367    }