View Javadoc
1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.util.concurrent;
16  
17  import com.google.common.annotations.GwtCompatible;
18  import java.util.concurrent.Executor;
19  import java.util.concurrent.Future;
20  import java.util.concurrent.RejectedExecutionException;
21  
22  /**
23   * A {@link Future} that accepts completion listeners. Each listener has an associated executor, and
24   * it is invoked using this executor once the future's computation is {@linkplain Future#isDone()
25   * complete}. If the computation has already completed when the listener is added, the listener will
26   * execute immediately.
27   *
28   * <p>See the Guava User Guide article on
29   * <a href="https://github.com/google/guava/wiki/ListenableFutureExplained">
30   * {@code ListenableFuture}</a>.
31   *
32   * <h3>Purpose</h3>
33   *
34   * <p>The main purpose of {@code ListenableFuture} is to help you chain together a graph of
35   * asynchronous operations. You can chain them together manually with calls to methods like
36   * {@link Futures#transform(ListenableFuture, com.google.common.base.Function, Executor)
37   * Futures.transform}, but you will often find it easier to use a framework. Frameworks automate the
38   * process, often adding features like monitoring, debugging, and cancellation. Examples of
39   * frameworks include:
40   *
41   * <ul>
42   * <li><a href="http://google.github.io/dagger/producers.html">Dagger Producers</a>
43   * </ul>
44   *
45   * <p>The main purpose of {@link #addListener addListener} is to support this chaining. You will
46   * rarely use it directly, in part because it does not provide direct access to the {@code Future}
47   * result. (If you want such access, you may prefer {@link Futures#addCallback
48   * Futures.addCallback}.) Still, direct {@code addListener} calls are occasionally useful:
49   *
50   * <pre>   {@code
51   *   final String name = ...;
52   *   inFlight.add(name);
53   *   ListenableFuture<Result> future = service.query(name);
54   *   future.addListener(new Runnable() {
55   *     public void run() {
56   *       processedCount.incrementAndGet();
57   *       inFlight.remove(name);
58   *       lastProcessed.set(name);
59   *       logger.info("Done with {0}", name);
60   *     }
61   *   }, executor);}</pre>
62   *
63   * <h3>How to get an instance</h3>
64   *
65   * <p>We encourage you to return {@code ListenableFuture} from your methods so that your users can
66   * take advantage of the {@linkplain Futures utilities built atop the class}. The way that you will
67   * create {@code ListenableFuture} instances depends on how you currently create {@code Future}
68   * instances:
69   * <ul>
70   * <li>If you receive them from an {@code java.util.concurrent.ExecutorService}, convert that
71   *     service to a {@link ListeningExecutorService}, usually by calling
72   *     {@link MoreExecutors#listeningDecorator(java.util.concurrent.ExecutorService)
73   *     MoreExecutors.listeningDecorator}.
74   * <li>If you manually call {@link java.util.concurrent.FutureTask#set} or a similar method, create
75   *     a {@link SettableFuture} instead. (If your needs are more complex, you may prefer
76   *     {@link AbstractFuture}.)
77   * </ul>
78   *
79   * <p><b>Test doubles</b>: If you need a {@code ListenableFuture} for your test, try a {@link
80   * SettableFuture} or one of the methods in the {@link Futures#immediateFuture Futures.immediate*}
81   * family. <b>Avoid</b> creating a mock or stub {@code Future}. Mock and stub implementations are
82   * fragile because they assume that only certain methods will be called and because they often
83   * implement subtleties of the API improperly.
84   *
85   * <p><b>Custom implementation</b>: Avoid implementing {@code ListenableFuture} from scratch. If you
86   * can't get by with the standard implementations, prefer to derive a new {@code Future} instance
87   * with the methods in {@link Futures} or, if necessary, to extend {@link AbstractFuture}.
88   *
89   * <p>Occasionally, an API will return a plain {@code Future} and it will be impossible to change
90   * the return type. For this case, we provide a more expensive workaround in {@code
91   * JdkFutureAdapters}. However, when possible, it is more efficient and reliable to create a {@code
92   * ListenableFuture} directly.
93   *
94   * @author Sven Mawson
95   * @author Nishant Thakkar
96   * @since 1.0
97   */
98  @GwtCompatible
99  public interface ListenableFuture<V> extends Future<V> {
100   /**
101    * Registers a listener to be {@linkplain Executor#execute(Runnable) run} on the given executor.
102    * The listener will run when the {@code Future}'s computation is {@linkplain Future#isDone()
103    * complete} or, if the computation is already complete, immediately.
104    *
105    * <p>There is no guaranteed ordering of execution of listeners, but any listener added through
106    * this method is guaranteed to be called once the computation is complete.
107    *
108    * <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown
109    * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception
110    * thrown by {@linkplain MoreExecutors#directExecutor direct execution}) will be caught and
111    * logged.
112    *
113    * <p>Note: For fast, lightweight listeners that would be safe to execute in any thread, consider
114    * {@link MoreExecutors#directExecutor}. Otherwise, avoid it. Heavyweight {@code directExecutor}
115    * listeners can cause problems, and these problems can be difficult to reproduce because they
116    * depend on timing. For example:
117    *
118    * <ul>
119    * <li>The listener may be executed by the caller of {@code addListener}. That caller may be a UI
120    * thread or other latency-sensitive thread. This can harm UI responsiveness.
121    * <li>The listener may be executed by the thread that completes this {@code Future}. That thread
122    * may be an internal system thread such as an RPC network thread. Blocking that thread may stall
123    * progress of the whole system. It may even cause a deadlock.
124    * <li>The listener may delay other listeners, even listeners that are not themselves {@code
125    * directExecutor} listeners.
126    * </ul>
127    *
128    * <p>This is the most general listener interface. For common operations performed using
129    * listeners, see {@link Futures}. For a simplified but general listener interface, see {@link
130    * Futures#addCallback addCallback()}.
131    *
132    * <p>Memory consistency effects: Actions in a thread prior to adding a listener <a
133    * href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5">
134    * <i>happen-before</i></a> its execution begins, perhaps in another thread.
135    *
136    * @param listener the listener to run when the computation is complete
137    * @param executor the executor to run the listener in
138    * @throws RejectedExecutionException if we tried to execute the listener immediately but the
139    *     executor rejected it.
140    */
141   void addListener(Runnable listener, Executor executor);
142 }