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