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.common.annotations.GwtCompatible;
018import java.util.concurrent.Executor;
019import java.util.concurrent.Future;
020import java.util.concurrent.RejectedExecutionException;
021
022/**
023 * A {@link Future} that accepts completion listeners. Each listener has an associated executor, and
024 * it is invoked using this executor once the future's computation is {@linkplain Future#isDone()
025 * complete}. If the computation has already completed when the listener is added, the listener will
026 * execute immediately.
027 *
028 * <p>See the Guava User Guide article on
029 * <a href="https://github.com/google/guava/wiki/ListenableFutureExplained">
030 * {@code ListenableFuture}</a>.
031 *
032 * <h3>Purpose</h3>
033 *
034 * <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of
035 * asynchronous operations. You can chain them together manually with calls to methods like
036 * {@link Futures#transform(ListenableFuture, Function, Executor) Futures.transform}, but you will
037 * often find it easier to use a framework. Frameworks automate the process, often adding features
038 * like monitoring, debugging, and cancellation. Examples of frameworks include:
039 *
040 * <ul>
041 * <li><a href="http://google.github.io/dagger/producers.html">Dagger Producers</a>
042 * </ul>
043 *
044 * <p>The main purpose of {@link #addListener addListener} is to support this chaining. You will
045 * rarely use it directly, in part because it does not provide direct access to the {@code Future}
046 * result. (If you want such access, you may prefer {@link Futures#addCallback
047 * Futures.addCallback}.) Still, direct {@code addListener} calls are occasionally useful:
048 *
049 * <pre>   {@code
050 *   final String name = ...;
051 *   inFlight.add(name);
052 *   ListenableFuture<Result> future = service.query(name);
053 *   future.addListener(new Runnable() {
054 *     public void run() {
055 *       processedCount.incrementAndGet();
056 *       inFlight.remove(name);
057 *       lastProcessed.set(name);
058 *       logger.info("Done with {0}", name);
059 *     }
060 *   }, executor);}</pre>
061 *
062 * <h3>How to get an instance</h3>
063 *
064 * <p>We encourage you to return {@code ListenableFuture} from your methods so that your users can
065 * take advantage of the {@linkplain Futures utilities built atop the class}. The way that you will
066 * create {@code ListenableFuture} instances depends on how you currently create {@code Future}
067 * instances:
068 * <ul>
069 * <li>If you receive them from an {@code java.util.concurrent.ExecutorService}, convert that
070 *     service to a {@link ListeningExecutorService}, usually by calling
071 *     {@link MoreExecutors#listeningDecorator(java.util.concurrent.ExecutorService)
072 *     MoreExecutors.listeningDecorator}.
073 * <li>If you manually call {@link java.util.concurrent.FutureTask#set} or a similar method, create
074 *     a {@link SettableFuture} instead. (If your needs are more complex, you may prefer
075 *     {@link AbstractFuture}.)
076 * </ul>
077 *
078 * <p><b>Test doubles</b>: If you need a {@code ListenableFuture} for your test, try a {@link
079 * SettableFuture} or one of the methods in the {@link Futures#immediateFuture Futures.immediate*}
080 * family. <b>Avoid</b> creating a mock or stub {@code Future}. Mock and stub implementations are
081 * fragile because they assume that only certain methods will be called and because they often
082 * implement subtleties of the API improperly.
083 *
084 * <p><b>Custom implementation</b>: Avoid implementing {@code ListenableFuture} from scratch. If you
085 * can't get by with the standard implementations, prefer to derive a new {@code Future} instance
086 * with the methods in {@link Futures} or, if necessary, to extend {@link AbstractFuture}.
087 *
088 * <p>Occasionally, an API will return a plain {@code Future} and it will be impossible to change
089 * the return type. For this case, we provide a more expensive workaround in {@code
090 * JdkFutureAdapters}. However, when possible, it is more efficient and reliable to create a {@code
091 * ListenableFuture} directly.
092 *
093 * @author Sven Mawson
094 * @author Nishant Thakkar
095 * @since 1.0
096 */
097@GwtCompatible
098public interface ListenableFuture<V> extends Future<V> {
099  /**
100   * Registers a listener to be {@linkplain Executor#execute(Runnable) run} on the given executor.
101   * The listener will run when the {@code Future}'s computation is {@linkplain Future#isDone()
102   * complete} or, if the computation is already complete, immediately.
103   *
104   * <p>There is no guaranteed ordering of execution of listeners, but any listener added through
105   * this method is guaranteed to be called once the computation is complete.
106   *
107   * <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown
108   * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception
109   * thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught and
110   * logged.
111   *
112   * <p>Note: For fast, lightweight listeners that would be safe to execute in any thread, consider
113   * {@link MoreExecutors#directExecutor}. Otherwise, avoid it. Heavyweight {@code directExecutor}
114   * listeners can cause problems, and these problems can be difficult to reproduce because they
115   * depend on timing. For example:
116   *
117   * <ul>
118   * <li>The listener may be executed by the caller of {@code addListener}. That caller may be a UI
119   * thread or other latency-sensitive thread. This can harm UI responsiveness.
120   * <li>The listener may be executed by the thread that completes this {@code Future}. That thread
121   * may be an internal system thread such as an RPC network thread. Blocking that thread may stall
122   * progress of the whole system. It may even cause a deadlock.
123   * <li>The listener may delay other listeners, even listeners that are not themselves {@code
124   * directExecutor} listeners.
125   * </ul>
126   *
127   * <p>This is the most general listener interface. For common operations performed using
128   * listeners, see {@link Futures}. For a simplified but general listener interface, see {@link
129   * Futures#addCallback addCallback()}.
130   *
131   * <p>Memory consistency effects: Actions in a thread prior to adding a listener <a
132   * href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5">
133   * <i>happen-before</i></a> its execution begins, perhaps in another thread.
134   *
135   * @param listener the listener to run when the computation is complete
136   * @param executor the executor to run the listener in
137   * @throws RejectedExecutionException if we tried to execute the listener immediately but the
138   *     executor rejected it.
139   */
140  void addListener(Runnable listener, Executor executor);
141}