Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2007 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.util.concurrent;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import  javax.annotation.Nullable;

An abstract implementation of the ListenableFuture interface. This class is preferable to java.util.concurrent.FutureTask for two reasons: It implements ListenableFuture, and it does not implement Runnable. (If you want a Runnable implementation of ListenableFuture, create a ListenableFutureTask, or submit your tasks to a ListeningExecutorService.)

This class implements all methods in ListenableFuture. Subclasses should provide a way to set the result of the computation through the protected methods set(Object) and setException(Throwable). Subclasses may also override interruptTask(), which will be invoked automatically if a call to cancel(boolean) cancel(true) succeeds in canceling the future.

AbstractFuture uses an AbstractQueuedSynchronizer to deal with concurrency issues and guarantee thread safety.

The state changing methods all return a boolean indicating success or failure in changing the future's state. Valid states are running, completed, failed, or cancelled.

This class uses an ExecutionList to guarantee that all registered listeners will be executed, either when the future finishes or, for listeners that are added after the future completes, immediately. Runnable-Executor pairs are stored in the execution list but are not necessarily executed in the order in which they were added. (If a listener is added after the Future is complete, it will be executed immediately, even if earlier listeners have not been executed. Additionally, executors need not guarantee FIFO execution, or different listeners may run in different executors.)

Author(s):
Sven Mawson
Since:
1.0
 
 public abstract class AbstractFuture<V> implements ListenableFuture<V> {

  
Synchronization control for AbstractFutures.
 
   private final Sync<V> sync = new Sync<V>();
 
   // The execution list to hold our executors.
   private final ExecutionList executionList = new ExecutionList();

  
Constructor for use by subclasses.
 
   protected AbstractFuture() {}
 
   /*
    * Improve the documentation of when InterruptedException is thrown. Our
    * behavior matches the JDK's, but the JDK's documentation is misleading.
    */
  

The default AbstractFuture implementation throws InterruptedException if the current thread is interrupted before or during the call, even if the value is already available.

Throws:
InterruptedException if the current thread was interrupted before or during the call (optional but recommended).
CancellationException
 
   @Override
   public V get(long timeoutTimeUnit unitthrows InterruptedException,
     return .get(unit.toNanos(timeout));
   }
 
   /*
   * Improve the documentation of when InterruptedException is thrown. Our
   * behavior matches the JDK's, but the JDK's documentation is misleading.
   */
  

The default AbstractFuture implementation throws InterruptedException if the current thread is interrupted before or during the call, even if the value is already available.

Throws:
InterruptedException if the current thread was interrupted before or during the call (optional but recommended).
CancellationException
  public V get() throws InterruptedExceptionExecutionException {
    return .get();
  }
  public boolean isDone() {
    return .isDone();
  }
  public boolean isCancelled() {
    return .isCancelled();
  }
  public boolean cancel(boolean mayInterruptIfRunning) {
    if (!.cancel(mayInterruptIfRunning)) {
      return false;
    }
    if (mayInterruptIfRunning) {
      interruptTask();
    }
    return true;
  }

  
Subclasses can override this method to implement interruption of the future's computation. The method is invoked automatically by a successful call to cancel(true).

The default implementation does nothing.

Since:
10.0
  protected void interruptTask() {
  }

  
Returns true if this future was cancelled with mayInterruptIfRunning set to true.

Since:
14.0
  protected final boolean wasInterrupted() {
    return .wasInterrupted();
  }

  

Since:
10.0
  public void addListener(Runnable listenerExecutor exec) {
    .add(listenerexec);
  }

  
Subclasses should invoke this method to set the result of the computation to value. This will set the state of the future to AbstractFuture.Sync.COMPLETED and invoke the listeners if the state was successfully changed.

Parameters:
value the value that was the result of the task.
Returns:
true if the state was successfully changed.
  protected boolean set(@Nullable V value) {
    boolean result = .set(value);
    if (result) {
      .execute();
    }
    return result;
  }

  
Subclasses should invoke this method to set the result of the computation to an error, throwable. This will set the state of the future to AbstractFuture.Sync.COMPLETED and invoke the listeners if the state was successfully changed.

Parameters:
throwable the exception that the task failed with.
Returns:
true if the state was successfully changed.
  protected boolean setException(Throwable throwable) {
    boolean result = .setException(checkNotNull(throwable));
    if (result) {
      .execute();
    }
    return result;
  }

  

Following the contract of AbstractQueuedSynchronizer we create a private subclass to hold the synchronizer. This synchronizer is used to implement the blocking and waiting calls as well as to handle state changes in a thread-safe manner. The current state of the future is held in the Sync state, and the lock is released whenever the state changes to COMPLETED, CANCELLED, or INTERRUPTED

To avoid races between threads doing release and acquire, we transition to the final state in two steps. One thread will successfully CAS from RUNNING to COMPLETING, that thread will then set the result of the computation, and only then transition to COMPLETED, CANCELLED, or INTERRUPTED.

We don't use the integer argument passed between acquire methods so we pass around a -1 everywhere.

  static final class Sync<V> extends AbstractQueuedSynchronizer {
    private static final long serialVersionUID = 0L;
    /* Valid states. */
    static final int RUNNING = 0;
    static final int COMPLETING = 1;
    static final int COMPLETED = 2;
    static final int CANCELLED = 4;
    static final int INTERRUPTED = 8;
    private V value;
    private Throwable exception;
    /*
     * Acquisition succeeds if the future is done, otherwise it fails.
     */
    @Override
    protected int tryAcquireShared(int ignored) {
      if (isDone()) {
        return 1;
      }
      return -1;
    }
    /*
     * We always allow a release to go through, this means the state has been
     * successfully changed and the result is available.
     */
    @Override
    protected boolean tryReleaseShared(int finalState) {
      setState(finalState);
      return true;
    }

    
Blocks until the task is complete or the timeout expires. Throws a TimeoutException if the timer expires, otherwise behaves like get().
    V get(long nanosthrows TimeoutExceptionCancellationException,
      // Attempt to acquire the shared lock with a timeout.
      if (!tryAcquireSharedNanos(-1, nanos)) {
        throw new TimeoutException("Timeout waiting for task.");
      }
      return getValue();
    }

    
Blocks until complete(Object, Throwable, int) has been successfully called. Throws a CancellationException if the task was cancelled, or a ExecutionException if the task completed with an error.
        InterruptedException {
      // Acquire the shared lock allowing interruption.
      return getValue();
    }

    
Implementation of the actual value retrieval. Will return the value on success, an exception on failure, a cancellation on cancellation, or an illegal state if the synchronizer is in an invalid state.
    private V getValue() throws CancellationExceptionExecutionException {
      int state = getState();
      switch (state) {
        case :
          if ( != null) {
            throw new ExecutionException();
          } else {
            return ;
          }
        case :
        case :
          throw cancellationExceptionWithCause(
              "Task was cancelled.");
        default:
          throw new IllegalStateException(
              "Error, synchronizer in invalid state: " + state);
      }
    }

    
Checks if the state is COMPLETED, CANCELLED, or INTERRUPTED.
    boolean isDone() {
      return (getState() & ( |  | )) != 0;
    }

    
Checks if the state is CANCELLED or INTERRUPTED.
    boolean isCancelled() {
      return (getState() & ( | )) != 0;
    }

    
Checks if the state is INTERRUPTED.
    boolean wasInterrupted() {
      return getState() == ;
    }

    
Transition to the COMPLETED state and set the value.
    boolean set(@Nullable V v) {
      return complete(vnull);
    }

    
Transition to the COMPLETED state and set the exception.
    boolean setException(Throwable t) {
      return complete(nullt);
    }

    
Transition to the CANCELLED or INTERRUPTED state.
    boolean cancel(boolean interrupt) {
      return complete(nullnullinterrupt ?  : );
    }

    
Implementation of completing a task. Either v or t will be set but not both. The finalState is the state to change to from RUNNING. If the state is not in the RUNNING state we return false after waiting for the state to be set to a valid final state (COMPLETED, CANCELLED, or INTERRUPTED).

Parameters:
v the value to set as the result of the computation.
t the exception to set as the result of the computation.
finalState the state to transition to.
    private boolean complete(@Nullable V v, @Nullable Throwable t,
        int finalState) {
      boolean doCompletion = compareAndSetState();
      if (doCompletion) {
        // If this thread successfully transitioned to COMPLETING, set the value
        // and exception and then release to the final state.
        this. = v;
        // Don't actually construct a CancellationException until necessary.
        this. = ((finalState & ( | )) != 0)
            ? new CancellationException("Future.cancel() was called.") : t;
        releaseShared(finalState);
      } else if (getState() == ) {
        // If some other thread is currently completing the future, block until
        // they are done so we can guarantee completion.
        acquireShared(-1);
      }
      return doCompletion;
    }
  }
      @Nullable String message, @Nullable Throwable cause) {
    CancellationException exception = new CancellationException(message);
    exception.initCause(cause);
    return exception;
  }
New to GrepCode? Check out our FAQ X