4
https://gist.github.com/2414323Java中是否存在ResolvedFuture類?
有時,您已經知道計算結果,但您的接口要求您返回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;
}
}