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