001/*
002 * Copyright (C) 2009 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 com.google.common.base.Preconditions.checkNotNull;
018import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
019import static java.util.concurrent.Executors.newCachedThreadPool;
020
021import com.google.common.annotations.GwtIncompatible;
022import com.google.common.annotations.J2ktIncompatible;
023import java.util.concurrent.Executor;
024import java.util.concurrent.Future;
025import java.util.concurrent.ThreadFactory;
026import java.util.concurrent.atomic.AtomicBoolean;
027import org.jspecify.annotations.Nullable;
028
029/**
030 * Utilities necessary for working with libraries that supply plain {@link Future} instances. Note
031 * that, whenever possible, it is strongly preferred to modify those libraries to return {@code
032 * ListenableFuture} directly.
033 *
034 * <p>For interoperability between {@code ListenableFuture} and <b>{@code CompletableFuture}</b>,
035 * consider <a href="https://github.com/lukas-krecan/future-converter">Future Converter</a>.
036 *
037 * @author Sven Mawson
038 * @since 10.0 (replacing {@code Futures.makeListenable}, which existed in 1.0)
039 */
040@J2ktIncompatible
041@GwtIncompatible
042public final class JdkFutureAdapters {
043  /**
044   * Assigns a thread to the given {@link Future} to provide {@link ListenableFuture} functionality.
045   *
046   * <p><b>Warning:</b> If the input future does not already implement {@code ListenableFuture}, the
047   * returned future will emulate {@link ListenableFuture#addListener} by taking a thread from an
048   * internal, unbounded pool at the first call to {@code addListener} and holding it until the
049   * future is {@linkplain Future#isDone() done}.
050   *
051   * <p>Prefer to create {@code ListenableFuture} instances with {@link SettableFuture}, {@link
052   * MoreExecutors#listeningDecorator(java.util.concurrent.ExecutorService)}, {@link
053   * ListenableFutureTask}, {@link AbstractFuture}, and other utilities over creating plain {@code
054   * Future} instances to be upgraded to {@code ListenableFuture} after the fact.
055   */
056  public static <V extends @Nullable Object> ListenableFuture<V> listenInPoolThread(
057      Future<V> future) {
058    if (future instanceof ListenableFuture) {
059      return (ListenableFuture<V>) future;
060    }
061    return new ListenableFutureAdapter<>(future);
062  }
063
064  /**
065   * Submits a blocking task for the given {@link Future} to provide {@link ListenableFuture}
066   * functionality.
067   *
068   * <p><b>Warning:</b> If the input future does not already implement {@code ListenableFuture}, the
069   * returned future will emulate {@link ListenableFuture#addListener} by submitting a task to the
070   * given executor at the first call to {@code addListener}. The task must be started by the
071   * executor promptly, or else the returned {@code ListenableFuture} may fail to work. The task's
072   * execution consists of blocking until the input future is {@linkplain Future#isDone() done}, so
073   * each call to this method may claim and hold a thread for an arbitrary length of time. Use of
074   * bounded executors or other executors that may fail to execute a task promptly may result in
075   * deadlocks.
076   *
077   * <p>Prefer to create {@code ListenableFuture} instances with {@link SettableFuture}, {@link
078   * MoreExecutors#listeningDecorator(java.util.concurrent.ExecutorService)}, {@link
079   * ListenableFutureTask}, {@link AbstractFuture}, and other utilities over creating plain {@code
080   * Future} instances to be upgraded to {@code ListenableFuture} after the fact.
081   *
082   * @since 12.0
083   */
084  public static <V extends @Nullable Object> ListenableFuture<V> listenInPoolThread(
085      Future<V> future, Executor executor) {
086    checkNotNull(executor);
087    if (future instanceof ListenableFuture) {
088      return (ListenableFuture<V>) future;
089    }
090    return new ListenableFutureAdapter<>(future, executor);
091  }
092
093  /**
094   * An adapter to turn a {@link Future} into a {@link ListenableFuture}. This will wait on the
095   * future to finish, and when it completes, run the listeners. This implementation will wait on
096   * the source future indefinitely, so if the source future never completes, the adapter will never
097   * complete either.
098   *
099   * <p>If the delegate future is interrupted or throws an unexpected unchecked exception, the
100   * listeners will not be invoked.
101   */
102  private static final class ListenableFutureAdapter<V extends @Nullable Object>
103      extends ForwardingFuture<V> implements ListenableFuture<V> {
104
105    private static final ThreadFactory threadFactory =
106        new ThreadFactoryBuilder()
107            .setDaemon(true)
108            .setNameFormat("ListenableFutureAdapter-thread-%d")
109            .build();
110    private static final Executor defaultAdapterExecutor = newCachedThreadPool(threadFactory);
111
112    private final Executor adapterExecutor;
113
114    // The execution list to hold our listeners.
115    private final ExecutionList executionList = new ExecutionList();
116
117    // This allows us to only start up a thread waiting on the delegate future when the first
118    // listener is added.
119    private final AtomicBoolean hasListeners = new AtomicBoolean(false);
120
121    // The delegate future.
122    private final Future<V> delegate;
123
124    ListenableFutureAdapter(Future<V> delegate) {
125      this(delegate, defaultAdapterExecutor);
126    }
127
128    ListenableFutureAdapter(Future<V> delegate, Executor adapterExecutor) {
129      this.delegate = checkNotNull(delegate);
130      this.adapterExecutor = checkNotNull(adapterExecutor);
131    }
132
133    @Override
134    protected Future<V> delegate() {
135      return delegate;
136    }
137
138    @Override
139    public void addListener(Runnable listener, Executor exec) {
140      executionList.add(listener, exec);
141
142      // When a listener is first added, we run a task that will wait for the delegate to finish,
143      // and when it is done will run the listeners.
144      if (hasListeners.compareAndSet(false, true)) {
145        if (delegate.isDone()) {
146          // If the delegate is already done, run the execution list immediately on the current
147          // thread.
148          executionList.execute();
149          return;
150        }
151
152        // TODO(lukes): handle RejectedExecutionException
153        adapterExecutor.execute(
154            () -> {
155              try {
156                /*
157                 * Threads from our private pool are never interrupted. Threads from a
158                 * user-supplied executor might be, but... what can we do? This is another reason
159                 * to return a proper ListenableFuture instead of using listenInPoolThread.
160                 */
161                getUninterruptibly(delegate);
162              } catch (Throwable t) {
163                // (including CancellationException and sneaky checked exception)
164                // The task is presumably done, run the listeners.
165                // TODO(cpovirk): Do *something* in case of Error (and maybe
166                // non-CancellationException, non-ExecutionException exceptions)?
167              }
168              executionList.execute();
169            });
170      }
171    }
172  }
173
174  private JdkFutureAdapters() {}
175}