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    
017    package com.google.common.util.concurrent;
018    
019    import java.util.concurrent.Executor;
020    import java.util.concurrent.ExecutorService;
021    import java.util.concurrent.Future;
022    import java.util.concurrent.FutureTask;
023    import java.util.concurrent.RejectedExecutionException;
024    
025    /**
026     * A {@link Future} that accepts completion listeners.  Each listener has an
027     * associated executor, and it is invoked using this executor once the future's
028     * computation is {@linkplain Future#isDone() complete}.  If the computation has
029     * already completed when the listener is added, the listener will execute
030     * immediately.
031     *
032     * <h3>Purpose</h3>
033     *
034     * Most commonly, {@code ListenableFuture} is used as an input to another
035     * derived {@code Future}, as in {@link Futures#allAsList(Iterable)
036     * Futures.allAsList}. Many such methods are impossible to implement efficiently
037     * without listener support.
038     *
039     * <p>It is possible to call {@link #addListener addListener} directly, but this
040     * is uncommon because the {@code Runnable} interface does not provide direct
041     * access to the {@code Future} result. (Users who want such access may prefer
042     * {@link Futures#addCallback Futures.addCallback}.) Still, direct {@code
043     * addListener} calls are occasionally useful:<pre>   {@code
044     *   final String name = ...;
045     *   inFlight.add(name);
046     *   ListenableFuture<Result> future = service.query(name);
047     *   future.addListener(new Runnable() {
048     *     public void run() {
049     *       processedCount.incrementAndGet();
050     *       inFlight.remove(name);
051     *       lastProcessed.set(name);
052     *       logger.info("Done with {0}", name);
053     *     }
054     *   }, executor);}</pre>
055     *
056     * <h3>How to get an instance</h3>
057     *
058     * Developers are encouraged to return {@code ListenableFuture} from their
059     * methods so that users can take advantages of the utilities built atop the
060     * class. The way that they will create {@code ListenableFuture} instances
061     * depends on how they currently create {@code Future} instances:
062     * <ul>
063     * <li>If they are returned from an {@code ExecutorService}, convert that
064     * service to a {@link ListeningExecutorService}, usually by calling {@link
065     * MoreExecutors#listeningDecorator(ExecutorService)
066     * MoreExecutors.listeningDecorator}. (Custom executors may find it more
067     * convenient to use {@link ListenableFutureTask} directly.)
068     * <li>If they are manually filled in by a call to {@link FutureTask#set} or a
069     * similar method, create a {@link SettableFuture} instead. (Users with more
070     * complex needs may prefer {@link AbstractFuture}.)
071     * </ul>
072     *
073     * Occasionally, an API will return a plain {@code Future} and it will be
074     * impossible to change the return type. For this case, we provide a more
075     * expensive workaround in {@code JdkFutureAdapters}. However, when possible, it
076     * is more efficient and reliable to create a {@code ListenableFuture} directly.
077     *
078     * @author Sven Mawson
079     * @author Nishant Thakkar
080     * @since 1.0
081     */
082    public interface ListenableFuture<V> extends Future<V> {
083      /**
084       * Registers a listener to be {@linkplain Executor#execute(Runnable) run} on
085       * the given executor.  The listener will run when the {@code Future}'s
086       * computation is {@linkplain Future#isDone() complete} or, if the computation
087       * is already complete, immediately.
088       *
089       * <p>There is no guaranteed ordering of execution of listeners, but any
090       * listener added through this method is guaranteed to be called once the
091       * computation is complete.
092       *
093       * <p>Exceptions thrown by a listener will be propagated up to the executor.
094       * Any exception thrown during {@code Executor.execute} (e.g., a {@code
095       * RejectedExecutionException} or an exception thrown by {@linkplain
096       * MoreExecutors#sameThreadExecutor inline execution}) will be caught and
097       * logged.
098       *
099       * <p>Note: For fast, lightweight listeners that would be safe to execute in
100       * any thread, consider {@link MoreExecutors#sameThreadExecutor}. For heavier
101       * listeners, {@code sameThreadExecutor()} carries some caveats: First, the
102       * thread that the listener runs in depends on whether the {@code Future} is
103       * done at the time it is added. In particular, if added late, listeners will
104       * run in the thread that called {@code addListener}. Second, listeners may
105       * run in an internal thread of the system responsible for the input {@code
106       * Future}, such as an RPC network thread. Finally, during the execution of a
107       * {@link MoreExecutors#sameThreadExecutor sameThreadExecutor} listener, all
108       * other registered but unexecuted listeners are prevented from running, even
109       * if those listeners are to run in other executors.
110       *
111       * <p>This is the most general listener interface.
112       * For common operations performed using listeners,
113       * see {@link com.google.common.util.concurrent.Futures}
114       *
115       * @param listener the listener to run when the computation is complete
116       * @param executor the executor to run the listener in
117       * @throws NullPointerException if the executor or listener was null
118       * @throws RejectedExecutionException if we tried to execute the listener
119       *         immediately but the executor rejected it.
120       */
121      void addListener(Runnable listener, Executor executor);
122    }