https://gist.github.com/2414323
有时,您已经知道计算结果,但您的界面要求您返回Future
。我发现创建一个实现Future
的小型持有者类更简单,而不是实现一个很长的匿名类,或者扩展本身很复杂的AbstractFuture或FutureTask。
我的问题是 - 在一个标准库中是否存在类似我下面写的类?
用法:
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;
}
}