https://gist.github.com/2414323
有时,您已经知道计算的结果,但您的界面要求您返回Future.我没有实现一个很长的匿名类,或扩展本身很复杂的AbstractFuture或FutureTask,而是发现创建一个实现Future的小型类更简单.
我的问题是 – 在一个标准库中是否存在类似我下面写的类?
用法:
Future iHaveToReturnAFutureButIAlreadyKnowTheAnswer() {
return new ResolvedFuture(true);
}
码:
/**
* Used when you need to return a Future, but you already have the answer.
*/
public class ResolvedFuture implements Future{
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;
}
}