https://gist.github.com/2414323
Sometimes, you already know the result of a computation, but your interface requires you to return a Future. Rather than implement a long anonymous class, or extend AbstractFuture or FutureTask which are themselves complicated, I find it simpler to just create a small holder class that implements Future.
My question is – does a class similar to what I wrote below already exist in one of the standard libraries?
Usage:
Future<Boolean> iHaveToReturnAFutureButIAlreadyKnowTheAnswer() {
return new ResolvedFuture(true);
}
Code:
/**
* 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;
}
}
Standard library doesn’t support it, but some third-party libraries may contains such an implementation. For example,
Futures.immediateFuture()from Google Guava.