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 com.google.common.annotations.Beta;
020
021 import java.util.concurrent.Callable;
022 import java.util.concurrent.Executor;
023 import java.util.concurrent.FutureTask;
024
025 /**
026 * A {@link FutureTask} that also implements the {@link ListenableFuture}
027 * interface. Subclasses must make sure to call {@code super.done()} if they
028 * also override the {@link #done()} method, otherwise the listeners will not
029 * be called.
030 *
031 * @author Sven Mawson
032 * @since 1
033 */
034 @Beta
035 public class ListenableFutureTask<V> extends FutureTask<V>
036 implements ListenableFuture<V> {
037
038 // The execution list to hold our listeners.
039 private final ExecutionList executionList = new ExecutionList();
040
041 /**
042 * Creates a {@code ListenableFutureTask} that will upon running, execute the
043 * given {@code Callable}.
044 *
045 * @param callable the callable task
046 * @throws NullPointerException if callable is null
047 */
048 public ListenableFutureTask(Callable<V> callable) {
049 super(callable);
050 }
051
052 /**
053 * Creates a {@code ListenableFutureTask} that will upon running, execute the
054 * given {@code Runnable}, and arrange that {@code get} will return the
055 * given result on successful completion.
056 *
057 * @param runnable the runnable task
058 * @param result the result to return on successful completion. If
059 * you don't need a particular result, consider using
060 * constructions of the form:
061 * {@code ListenableFuture<?> f =
062 * new ListenableFutureTask<Object>(runnable, null)}
063 * @throws NullPointerException if runnable is null
064 */
065 public ListenableFutureTask(Runnable runnable, V result) {
066 super(runnable, result);
067 }
068
069 @Override
070 public void addListener(Runnable listener, Executor exec) {
071 executionList.add(listener, exec);
072 }
073
074 @Override
075 protected void done() {
076 executionList.run();
077 }
078 }