1 /* 2 * Copyright (C) 2008 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.Callable; 20 import java.util.concurrent.Executor; 21 import java.util.concurrent.FutureTask; 22 23 /** 24 * A {@link FutureTask} that also implements the {@link ListenableFuture} 25 * interface. Subclasses must make sure to call {@code super.done()} if they 26 * also override the {@link #done()} method, otherwise the listeners will not 27 * be called. 28 * 29 * @author Sven Mawson 30 * @since 2009.09.15 <b>tentative</b> 31 */ 32 public class ListenableFutureTask<V> extends FutureTask<V> 33 implements ListenableFuture<V> { 34 35 // The execution list to hold our listeners. 36 private final ExecutionList executionList = new ExecutionList(); 37 38 /** 39 * Creates a {@code ListenableFutureTask} that will upon running, execute the 40 * given {@code Callable}. 41 * 42 * @param callable the callable task 43 * @throws NullPointerException if callable is null 44 */ 45 public ListenableFutureTask(Callable<V> callable) { 46 super(callable); 47 } 48 49 /** 50 * Creates a {@code ListenableFutureTask} that will upon running, execute the 51 * given {@code Runnable}, and arrange that {@code get} will return the 52 * given result on successful completion. 53 * 54 * @param runnable the runnable task 55 * @param result the result to return on successful completion. If 56 * you don't need a particular result, consider using 57 * constructions of the form: 58 * {@code ListenableFuture<?> f = 59 * new ListenableFutureTask<Object>(runnable, null)} 60 * @throws NullPointerException if runnable is null 61 */ 62 public ListenableFutureTask(Runnable runnable, V result) { 63 super(runnable, result); 64 } 65 66 public void addListener(Runnable listener, Executor exec) { 67 executionList.add(listener, exec); 68 } 69 70 @Override 71 protected void done() { 72 executionList.run(); 73 } 74 } 75