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