001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.util.concurrent;
018
019import com.google.common.annotations.GwtCompatible;
020
021import java.util.concurrent.Executor;
022import java.util.concurrent.ExecutorService;
023import java.util.concurrent.Future;
024import java.util.concurrent.FutureTask;
025import java.util.concurrent.RejectedExecutionException;
026
027/**
028 * A {@link Future} that accepts completion listeners.  Each listener has an
029 * associated executor, and it is invoked using this executor once the future's
030 * computation is {@linkplain Future#isDone() complete}.  If the computation has
031 * already completed when the listener is added, the listener will execute
032 * immediately.
033 * 
034 * <p>See the Guava User Guide article on <a href=
035 * "https://github.com/google/guava/wiki/ListenableFutureExplained">
036 * {@code ListenableFuture}</a>.
037 *
038 * <h3>Purpose</h3>
039 *
040 * <p>Most commonly, {@code ListenableFuture} is used as an input to another
041 * derived {@code Future}, as in {@link Futures#allAsList(Iterable)
042 * Futures.allAsList}. Many such methods are impossible to implement efficiently
043 * without listener support.
044 *
045 * <p>It is possible to call {@link #addListener addListener} directly, but this
046 * is uncommon because the {@code Runnable} interface does not provide direct
047 * access to the {@code Future} result. (Users who want such access may prefer
048 * {@link Futures#addCallback Futures.addCallback}.) Still, direct {@code
049 * addListener} calls are occasionally useful:<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>Developers are encouraged to return {@code ListenableFuture} from their
065 * methods so that users can take advantages of the {@linkplain Futures
066 * utilities built atop the class}. The way that they will create {@code
067 * ListenableFuture} instances depends on how they currently create {@code
068 * Future} instances:
069 * <ul>
070 * <li>If they are returned from an {@code ExecutorService}, convert that
071 * service to a {@link ListeningExecutorService}, usually by calling {@link
072 * MoreExecutors#listeningDecorator(ExecutorService)
073 * MoreExecutors.listeningDecorator}. (Custom executors may find it more
074 * convenient to use {@link ListenableFutureTask} directly.)
075 * <li>If they are manually filled in by a call to {@link FutureTask#set} or a
076 * similar method, create a {@link SettableFuture} instead. (Users with more
077 * complex needs may prefer {@link AbstractFuture}.)
078 * </ul>
079 *
080 * <p>Occasionally, an API will return a plain {@code Future} and it will be
081 * impossible to change the return type. For this case, we provide a more
082 * expensive workaround in {@code JdkFutureAdapters}. However, when possible, it
083 * is more efficient and reliable to create a {@code ListenableFuture} directly.
084 *
085 * @author Sven Mawson
086 * @author Nishant Thakkar
087 * @since 1.0
088 */
089@GwtCompatible
090public interface ListenableFuture<V> extends Future<V> {
091  /**
092   * Registers a listener to be {@linkplain Executor#execute(Runnable) run} on
093   * the given executor.  The listener will run when the {@code Future}'s
094   * computation is {@linkplain Future#isDone() complete} or, if the computation
095   * is already complete, immediately.
096   *
097   * <p>There is no guaranteed ordering of execution of listeners, but any
098   * listener added through this method is guaranteed to be called once the
099   * computation is complete.
100   *
101   * <p>Exceptions thrown by a listener will be propagated up to the executor.
102   * Any exception thrown during {@code Executor.execute} (e.g., a {@code
103   * RejectedExecutionException} or an exception thrown by {@linkplain
104   * MoreExecutors#directExecutor direct execution}) will be caught and
105   * logged.
106   *
107   * <p>Note: For fast, lightweight listeners that would be safe to execute in
108   * any thread, consider {@link MoreExecutors#directExecutor}. Otherwise, avoid
109   * it. Heavyweight {@code directExecutor} listeners can cause problems, and
110   * these problems can be difficult to reproduce because they depend on timing.
111   * For example:
112   *
113   * <ul>
114   * <li>The listener may be executed by the caller of {@code addListener}. That
115   * caller may be a UI thread or other latency-sensitive thread. This can harm
116   * UI responsiveness.
117   * <li>The listener may be executed by the thread that completes this {@code
118   * Future}. That thread may be an internal system thread such as an RPC
119   * network thread. Blocking that thread may stall progress of the whole
120   * system. It may even cause a deadlock.
121   * <li>The listener may delay other listeners, even listeners that are not
122   * themselves {@code directExecutor} listeners.
123   * </ul>
124   *
125   * <p>This is the most general listener interface. For common operations
126   * performed using listeners, see {@link Futures}. For a simplified but
127   * general listener interface, see {@link Futures#addCallback addCallback()}.
128   *
129   * <p>Memory consistency effects: Actions in a thread prior to adding a listener
130   * <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5">
131   * <i>happen-before</i></a> its execution begins, perhaps in another thread.
132   *
133   * @param listener the listener to run when the computation is complete
134   * @param executor the executor to run the listener in
135   * @throws NullPointerException if the executor or listener was null
136   * @throws RejectedExecutionException if we tried to execute the listener
137   *         immediately but the executor rejected it.
138   */
139  void addListener(Runnable listener, Executor executor);
140}