1 /* 2 * Copyright (C) 2007 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.util.concurrent; 18 19 import java.util.concurrent.Executor; 20 import java.util.concurrent.Future; 21 import java.util.concurrent.RejectedExecutionException; 22 23 /** 24 * <p>This interface defines a future that has listeners attached to it, which 25 * is useful for asynchronous workflows. Each listener has an associated 26 * executor, and is invoked using this executor once the {@code Future}'s 27 * computation is {@linkplain Future#isDone() complete}. The listener will be 28 * executed even if it is added after the computation is complete. 29 * 30 * <p>Usage: 31 * <pre> {@code 32 * final ListenableFuture<?> future = myService.async(myRequest); 33 * future.addListener(new Runnable() { 34 * public void run() { 35 * System.out.println("Operation Complete."); 36 * try { 37 * System.out.println("Result: " + future.get()); 38 * } catch (Exception e) { 39 * System.out.println("Error: " + e.message()); 40 * } 41 * } 42 * }, exec);}</pre> 43 * 44 * @author Sven Mawson 45 * @author Nishant Thakkar 46 * @since 2009.09.15 <b>tentative</b> 47 */ 48 public interface ListenableFuture<V> extends Future<V> { 49 50 /** 51 * <p>Adds a listener and executor to the ListenableFuture. 52 * The listener will be {@linkplain Executor#execute(Runnable) passed 53 * to the executor} for execution when the {@code Future}'s computation is 54 * {@linkplain Future#isDone() complete}. 55 * 56 * <p>There is no guaranteed ordering of execution of listeners, they may get 57 * called in the order they were added and they may get called out of order, 58 * but any listener added through this method is guaranteed to be called once 59 * the computation is complete. 60 * 61 * @param listener the listener to run when the computation is complete. 62 * @param exec the executor to run the listener in. 63 * @throws NullPointerException if the executor or listener was null. 64 * @throws RejectedExecutionException if we tried to execute the listener 65 * immediately but the executor rejected it. 66 */ addListener(Runnable listener, Executor exec)67 public void addListener(Runnable listener, Executor exec); 68 } 69