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