001/*
002 * Copyright (C) 2008 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 java.lang.Math.min;
018import static java.util.concurrent.TimeUnit.NANOSECONDS;
019
020import com.google.common.annotations.GwtIncompatible;
021import com.google.errorprone.annotations.CanIgnoreReturnValue;
022import java.util.concurrent.Callable;
023import java.util.concurrent.ExecutionException;
024import java.util.concurrent.Executor;
025import java.util.concurrent.FutureTask;
026import java.util.concurrent.TimeUnit;
027import java.util.concurrent.TimeoutException;
028import org.checkerframework.checker.nullness.qual.Nullable;
029
030/**
031 * A {@link FutureTask} that also implements the {@link ListenableFuture} interface. Unlike {@code
032 * FutureTask}, {@code ListenableFutureTask} does not provide an overrideable {@link
033 * FutureTask#done() done()} method. For similar functionality, call {@link #addListener}.
034 *
035 * <p>Few users should use this class. It is intended primarily for those who are implementing an
036 * {@code ExecutorService}. Most users should call {@link ListeningExecutorService#submit(Callable)
037 * ListeningExecutorService.submit} on a service obtained from {@link
038 * MoreExecutors#listeningDecorator}.
039 *
040 * @author Sven Mawson
041 * @since 1.0
042 */
043@GwtIncompatible
044@ElementTypesAreNonnullByDefault
045public class ListenableFutureTask<V extends @Nullable Object> extends FutureTask<V>
046    implements ListenableFuture<V> {
047  // TODO(cpovirk): explore ways of making ListenableFutureTask final. There are some valid reasons
048  // such as BoundedQueueExecutorService to allow extends but it would be nice to make it final to
049  // avoid unintended usage.
050
051  // The execution list to hold our listeners.
052  private final ExecutionList executionList = new ExecutionList();
053
054  /**
055   * Creates a {@code ListenableFutureTask} that will upon running, execute the given {@code
056   * Callable}.
057   *
058   * @param callable the callable task
059   * @since 10.0
060   */
061  public static <V extends @Nullable Object> ListenableFutureTask<V> create(Callable<V> callable) {
062    return new ListenableFutureTask<V>(callable);
063  }
064
065  /**
066   * Creates a {@code ListenableFutureTask} that will upon running, execute the given {@code
067   * Runnable}, and arrange that {@code get} will return the given result on successful completion.
068   *
069   * @param runnable the runnable task
070   * @param result the result to return on successful completion. If you don't need a particular
071   *     result, consider using constructions of the form: {@code ListenableFuture<?> f =
072   *     ListenableFutureTask.create(runnable, null)}
073   * @since 10.0
074   */
075  public static <V extends @Nullable Object> ListenableFutureTask<V> create(
076      Runnable runnable, @ParametricNullness V result) {
077    return new ListenableFutureTask<V>(runnable, result);
078  }
079
080  ListenableFutureTask(Callable<V> callable) {
081    super(callable);
082  }
083
084  ListenableFutureTask(Runnable runnable, @ParametricNullness V result) {
085    super(runnable, result);
086  }
087
088  @Override
089  public void addListener(Runnable listener, Executor exec) {
090    executionList.add(listener, exec);
091  }
092
093  @CanIgnoreReturnValue
094  @Override
095  @ParametricNullness
096  public V get(long timeout, TimeUnit unit)
097      throws TimeoutException, InterruptedException, ExecutionException {
098
099    long timeoutNanos = unit.toNanos(timeout);
100    if (timeoutNanos <= OverflowAvoidingLockSupport.MAX_NANOSECONDS_THRESHOLD) {
101      return super.get(timeout, unit);
102    }
103    // Waiting 68 years should be enough for any program.
104    return super.get(
105        min(timeoutNanos, OverflowAvoidingLockSupport.MAX_NANOSECONDS_THRESHOLD), NANOSECONDS);
106  }
107
108  /** Internal implementation detail used to invoke the listeners. */
109  @Override
110  protected void done() {
111    executionList.execute();
112  }
113}