Jake Walsh Jake Walsh - 3 months ago 34
Java Question

how to create a completed future in java

What is the best way to construct a completed future in java? I have implemented my own CompletedFuture below, but was hoping something like this that already exists.

public class CompletedFuture<T> implements Future<T> {
private final T result;

public CompletedFuture(final T result) {
this.result = result;
}

@Override
public boolean cancel(final boolean b) {
return false;
}

@Override
public boolean isCancelled() {
return false;
}

@Override
public boolean isDone() {
return true;
}

@Override
public T get() throws InterruptedException, ExecutionException {
return this.result;
}

@Override
public T get(final long l, final TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
return get();
}
}

Answer

Apache Commons Lang defines similar implementation that is called ConstantFuture, you can get it by calling:

Future<T> future = ConcurrentUtils.constantFuture(T myValue);
Comments