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
044public class ListenableFutureTask<V> extends FutureTask<V> implements ListenableFuture<V> {
045  // TODO(cpovirk): explore ways of making ListenableFutureTask final. There are some valid reasons
046  // such as BoundedQueueExecutorService to allow extends but it would be nice to make it final to
047  // avoid unintended usage.
048
049  // The execution list to hold our listeners.
050  private final ExecutionList executionList = new ExecutionList();
051
052  /**
053   * Creates a {@code ListenableFutureTask} that will upon running, execute the given {@code
054   * Callable}.
055   *
056   * @param callable the callable task
057   * @since 10.0
058   */
059  public static <V> ListenableFutureTask<V> create(Callable<V> callable) {
060    return new ListenableFutureTask<V>(callable);
061  }
062
063  /**
064   * Creates a {@code ListenableFutureTask} that will upon running, execute the given {@code
065   * Runnable}, and arrange that {@code get} will return the given result on successful completion.
066   *
067   * @param runnable the runnable task
068   * @param result the result to return on successful completion. If you don't need a particular
069   *     result, consider using constructions of the form: {@code ListenableFuture<?> f =
070   *     ListenableFutureTask.create(runnable, null)}
071   * @since 10.0
072   */
073  public static <V> ListenableFutureTask<V> create(Runnable runnable, @Nullable V result) {
074    return new ListenableFutureTask<V>(runnable, result);
075  }
076
077  ListenableFutureTask(Callable<V> callable) {
078    super(callable);
079  }
080
081  ListenableFutureTask(Runnable runnable, @Nullable V result) {
082    super(runnable, result);
083  }
084
085  @Override
086  public void addListener(Runnable listener, Executor exec) {
087    executionList.add(listener, exec);
088  }
089
090  @CanIgnoreReturnValue
091  @Override
092  public V get(long timeout, TimeUnit unit)
093      throws TimeoutException, InterruptedException, ExecutionException {
094
095    long timeoutNanos = unit.toNanos(timeout);
096    if (timeoutNanos <= OverflowAvoidingLockSupport.MAX_NANOSECONDS_THRESHOLD) {
097      return super.get(timeout, unit);
098    }
099    // Waiting 68 years should be enough for any program.
100    return super.get(
101        min(timeoutNanos, OverflowAvoidingLockSupport.MAX_NANOSECONDS_THRESHOLD), NANOSECONDS);
102  }
103
104  /** Internal implementation detail used to invoke the listeners. */
105  @Override
106  protected void done() {
107    executionList.execute();
108  }
109}