https://gist.github.com/2414323
有时,您已经知道计算的结果,但您的界面要求您返回一个Future
. 与其实现一个长的匿名类,或者扩展本身很复杂的 AbstractFuture 或 FutureTask ,我发现只创建一个实现Future
.
我的问题是 - 与我在下面写的类似的类是否已经存在于一个标准库中?
用法:
Future<Boolean> iHaveToReturnAFutureButIAlreadyKnowTheAnswer() {
return new ResolvedFuture(true);
}
代码:
/**
* Used when you need to return a Future, but you already have the answer.
*/
public class ResolvedFuture<T> implements Future<T>{
private final T item;
public ResolvedFuture(T item) {
this.item = item;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public T get() throws InterruptedException, ExecutionException {
return item;
}
@Override
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return item;
}
}