001 /* 002 * Copyright (C) 2007 Google Inc. 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 com.google.common.annotations.Beta; 020 021 import java.util.concurrent.Executor; 022 import java.util.concurrent.Future; 023 import java.util.concurrent.RejectedExecutionException; 024 025 /** 026 * <p>This interface defines a future that has listeners attached to it, which 027 * is useful for asynchronous workflows. Each listener has an associated 028 * executor, and is invoked using this executor once the {@code Future}'s 029 * computation is {@linkplain Future#isDone() complete}. The listener will be 030 * executed even if it is added after the computation is complete. 031 * 032 * <p>Usage: 033 * <pre> {@code 034 * final ListenableFuture<?> future = myService.async(myRequest); 035 * future.addListener(new Runnable() { 036 * public void run() { 037 * System.out.println("Operation Complete."); 038 * try { 039 * System.out.println("Result: " + future.get()); 040 * } catch (Exception e) { 041 * System.out.println("Error: " + e.message()); 042 * } 043 * } 044 * }, exec);}</pre> 045 * 046 * @author Sven Mawson 047 * @author Nishant Thakkar 048 * @since 1 049 */ 050 @Beta 051 public interface ListenableFuture<V> extends Future<V> { 052 /** 053 * <p>Adds a listener and executor to the ListenableFuture. 054 * The listener will be {@linkplain Executor#execute(Runnable) passed 055 * to the executor} for execution when the {@code Future}'s computation is 056 * {@linkplain Future#isDone() complete}. 057 * 058 * <p>There is no guaranteed ordering of execution of listeners, they may get 059 * called in the order they were added and they may get called out of order, 060 * but any listener added through this method is guaranteed to be called once 061 * the computation is complete. 062 * 063 * @param listener the listener to run when the computation is complete. 064 * @param exec the executor to run the listener in. 065 * @throws NullPointerException if the executor or listener was null. 066 * @throws RejectedExecutionException if we tried to execute the listener 067 * immediately but the executor rejected it. 068 */ 069 void addListener(Runnable listener, Executor exec); 070 }