001 /* 002 * Copyright (C) 2008 The Guava Authors 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 java.util.concurrent.Callable; 020 import java.util.concurrent.Executor; 021 import java.util.concurrent.FutureTask; 022 023 import javax.annotation.Nullable; 024 025 /** 026 * A {@link FutureTask} that also implements the {@link ListenableFuture} 027 * interface. Unlike {@code FutureTask}, {@code ListenableFutureTask} does not 028 * provide an overrideable {@link FutureTask#done() done()} method. For similar 029 * functionality, call {@link #addListener}. 030 * 031 * @author Sven Mawson 032 * @since 1.0 033 */ 034 public final class ListenableFutureTask<V> extends FutureTask<V> 035 implements ListenableFuture<V> { 036 037 // The execution list to hold our listeners. 038 private final ExecutionList executionList = new ExecutionList(); 039 040 /** 041 * Creates a {@code ListenableFutureTask} that will upon running, execute the 042 * given {@code Callable}. 043 * 044 * @param callable the callable task 045 * @since 10.0 046 */ 047 public static <V> ListenableFutureTask<V> create(Callable<V> callable) { 048 return new ListenableFutureTask<V>(callable); 049 } 050 051 /** 052 * Creates a {@code ListenableFutureTask} that will upon running, execute the 053 * given {@code Runnable}, and arrange that {@code get} will return the 054 * given result on successful completion. 055 * 056 * @param runnable the runnable task 057 * @param result the result to return on successful completion. If you don't 058 * need a particular result, consider using constructions of the form: 059 * {@code ListenableFuture<?> f = ListenableFutureTask.create(runnable, 060 * null)} 061 * @since 10.0 062 */ 063 public static <V> ListenableFutureTask<V> create( 064 Runnable runnable, @Nullable V result) { 065 return new ListenableFutureTask<V>(runnable, result); 066 } 067 068 private ListenableFutureTask(Callable<V> callable) { 069 super(callable); 070 } 071 072 private ListenableFutureTask(Runnable runnable, @Nullable V result) { 073 super(runnable, result); 074 } 075 076 @Override 077 public void addListener(Runnable listener, Executor exec) { 078 executionList.add(listener, exec); 079 } 080 081 /** 082 * Internal implementation detail used to invoke the listeners. 083 */ 084 @Override 085 protected void done() { 086 executionList.execute(); 087 } 088 }