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