001/*
002 * Copyright (C) 2007 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 com.google.errorprone.annotations.DoNotMock;
018import java.util.concurrent.Executor;
019import java.util.concurrent.Future;
020import java.util.concurrent.RejectedExecutionException;
021import org.jspecify.annotations.NullMarked;
022import org.jspecify.annotations.Nullable;
023
024/**
025 * A {@link Future} that accepts completion listeners. Each listener has an associated executor, and
026 * it is invoked using this executor once the future's computation is {@linkplain Future#isDone()
027 * complete}. If the computation has already completed when the listener is added, the listener will
028 * execute immediately.
029 *
030 * <p>See the Guava User Guide article on <a
031 * href="https://github.com/google/guava/wiki/ListenableFutureExplained">{@code
032 * ListenableFuture}</a>.
033 *
034 * <p>This class is GWT-compatible.
035 *
036 * <h2>Purpose</h2>
037 *
038 * <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of
039 * asynchronous operations. You can chain them together manually with calls to methods like {@link
040 * Futures#transform(ListenableFuture, com.google.common.base.Function, Executor) Futures.transform}
041 * (or {@link FluentFuture#transform(com.google.common.base.Function, Executor)
042 * FluentFuture.transform}), but you will often find it easier to use a framework. Frameworks
043 * automate the process, often adding features like monitoring, debugging, and cancellation.
044 * Examples of frameworks include:
045 *
046 * <ul>
047 *   <li><a href="https://dagger.dev/producers.html">Dagger Producers</a>
048 * </ul>
049 *
050 * <p>If the operations in your chain create objects that must be closed when the computation is
051 * done, such as database connections or file handles, consider {@link ClosingFuture}. It closes
052 * them once the whole computation completes, fails, or is cancelled.
053 *
054 * <p>The main purpose of {@link #addListener addListener} is to support this chaining. You will
055 * rarely use it directly, in part because it does not provide direct access to the {@code Future}
056 * result. (If you want such access, you may prefer {@link Futures#addCallback
057 * Futures.addCallback}.) Still, direct {@code addListener} calls are occasionally useful:
058 *
059 * {@snippet :
060 * final String name = ...;
061 * inFlight.add(name);
062 * ListenableFuture<Result> future = service.query(name);
063 * future.addListener(new Runnable() {
064 *   public void run() {
065 *     processedCount.incrementAndGet();
066 *     inFlight.remove(name);
067 *     lastProcessed.set(name);
068 *     logger.info("Done with {0}", name);
069 *   }
070 * }, executor);
071 * }
072 *
073 * <h2>How to get an instance</h2>
074 *
075 * <p>We encourage you to return {@code ListenableFuture} from your methods so that your users can
076 * take advantage of the {@linkplain Futures utilities built atop the class}. The way that you will
077 * create {@code ListenableFuture} instances depends on how you currently create {@code Future}
078 * instances:
079 *
080 * <ul>
081 *   <li>If you receive them from an {@code java.util.concurrent.ExecutorService}, convert that
082 *       service to a {@link ListeningExecutorService}, usually by calling {@link
083 *       MoreExecutors#listeningDecorator(java.util.concurrent.ExecutorService)
084 *       MoreExecutors.listeningDecorator}.
085 *   <li>If you manually call {@link java.util.concurrent.FutureTask#set} or a similar method,
086 *       create a {@link SettableFuture} instead. (If your needs are more complex, you may prefer
087 *       {@link AbstractFuture}.)
088 * </ul>
089 *
090 * <p><b>Test doubles</b>: If you need a {@code ListenableFuture} for your test, try a {@link
091 * SettableFuture} or one of the methods in the {@link Futures#immediateFuture Futures.immediate*}
092 * family. <b>Avoid</b> creating a mock or stub {@code Future}. Mock and stub implementations are
093 * fragile because they assume that only certain methods will be called and because they often
094 * implement subtleties of the API improperly.
095 *
096 * <p><b>Custom implementation</b>: Avoid implementing {@code ListenableFuture} from scratch. If you
097 * can't get by with the standard implementations, prefer to derive a new {@code Future} instance
098 * with the methods in {@link Futures} or, if necessary, to extend {@link AbstractFuture}.
099 *
100 * <p>Occasionally, an API will return a plain {@code Future} and it will be impossible to change
101 * the return type. For this case, we provide a more expensive workaround in {@code
102 * JdkFutureAdapters}. However, when possible, it is more efficient and reliable to create a {@code
103 * ListenableFuture} directly.
104 *
105 * @author Sven Mawson
106 * @author Nishant Thakkar
107 * @since 1.0
108 */
109/*
110 * Some of the annotations below were added after we released our separate
111 * com.google.guava:listenablefuture:1.0 artifact. (For more on that artifact, see
112 * https://github.com/google/guava/releases/tag/v27.0) This means that the copy of ListenableFuture
113 * in com.google.guava:guava differs from the "frozen" copy in the listenablefuture artifact. This
114 * could in principle cause problems for some users. Still, we expect that the benefits of the
115 * nullness annotations in particular will outweigh the costs. (And it's worth noting that we have
116 * released multiple ListenableFuture.class files that are not byte-for-byte compatible even from
117 * the beginning, thanks to using different `-source -target` values for compiling our `-jre` and
118 * `-android` "flavors.")
119 *
120 * (We could consider releasing a listenablefuture:1.0.1 someday. But we would want to look into how
121 * that affects users, especially users of the Android Gradle Plugin, since the plugin developers
122 * put in a special hack for us: https://issuetracker.google.com/issues/131431257)
123 */
124@DoNotMock("Use the methods in Futures (like immediateFuture) or SettableFuture")
125@NullMarked
126public interface ListenableFuture<V extends @Nullable Object> extends Future<V> {
127  /**
128   * Registers a listener to be {@linkplain Executor#execute(Runnable) run} on the given executor.
129   * The listener will run when the {@code Future}'s computation is {@linkplain Future#isDone()
130   * complete} or, if the computation is already complete, immediately.
131   *
132   * <p>There is no guaranteed ordering of execution of listeners, but any listener added through
133   * this method is guaranteed to be called once the computation is complete.
134   *
135   * <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown
136   * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception
137   * thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught and
138   * logged.
139   *
140   * <p>Note: If your listener is lightweight -- and will not cause stack overflow by completing
141   * more futures or adding more {@code directExecutor()} listeners inline -- consider {@link
142   * MoreExecutors#directExecutor}. Otherwise, avoid it: See the warnings on the docs for {@code
143   * directExecutor}.
144   *
145   * <p>This is the most general listener interface. For common operations performed using
146   * listeners, see {@link Futures}. For a simplified but general listener interface, see {@link
147   * Futures#addCallback addCallback()}.
148   *
149   * <p>Memory consistency effects: Actions in a thread prior to adding a listener <a
150   * href="https://docs.oracle.com/javase/specs/jls/se27/html/jls-17.html#jls-17.4.5">
151   * <i>happen-before</i></a> its execution begins, perhaps in another thread.
152   *
153   * <p>Guava implementations of {@code ListenableFuture} promptly release references to listeners
154   * after executing them.
155   *
156   * @param listener the listener to run when the computation is complete
157   * @param executor the executor to run the listener in
158   * @throws RejectedExecutionException if we tried to execute the listener immediately but the
159   *     executor rejected it.
160   */
161  void addListener(Runnable listener, Executor executor);
162}