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 * <p>
032 *
033 * @author Sven Mawson
034 * @since 1.0
035 */
036 public final class ListenableFutureTask<V> extends FutureTask<V>
037 implements ListenableFuture<V> {
038
039 // The execution list to hold our listeners.
040 private final ExecutionList executionList = new ExecutionList();
041
042 /**
043 * Creates a {@code ListenableFutureTask} that will upon running, execute the
044 * given {@code Callable}.
045 *
046 * @param callable the callable task
047 * @since 10.0
048 */
049 public static <V> ListenableFutureTask<V> create(Callable<V> callable) {
050 return new ListenableFutureTask<V>(callable);
051 }
052
053 /**
054 * Creates a {@code ListenableFutureTask} that will upon running, execute the
055 * given {@code Runnable}, and arrange that {@code get} will return the
056 * given result on successful completion.
057 *
058 * @param runnable the runnable task
059 * @param result the result to return on successful completion. If you don't
060 * need a particular result, consider using constructions of the form:
061 * {@code ListenableFuture<?> f = ListenableFutureTask.create(runnable,
062 * null)}
063 * @since 10.0
064 */
065 public static <V> ListenableFutureTask<V> create(
066 Runnable runnable, @Nullable V result) {
067 return new ListenableFutureTask<V>(runnable, result);
068 }
069
070 private ListenableFutureTask(Callable<V> callable) {
071 super(callable);
072 }
073
074 private ListenableFutureTask(Runnable runnable, @Nullable V result) {
075 super(runnable, result);
076 }
077
078 @Override
079 public void addListener(Runnable listener, Executor exec) {
080 executionList.add(listener, exec);
081 }
082
083 /**
084 * Internal implementation detail used to invoke the listeners.
085 */
086 @Override
087 protected void done() {
088 executionList.execute();
089 }
090 }