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(); } }
The main implementation of the Future interface is the FutureTask class. It is used by the ExecutorService classes to represent a submitted job, etc.. Callable (like Runnable ) is a simple interface that you implement yourself. It wraps a task that you want the ExecutorService thread-pools to execute.
A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.
Future vs CompletableFuture. CompletableFuture is an extension to Java's Future API which was introduced in Java 5. A Future is used as a reference to the result of an asynchronous computation.
Limitations of the FutureFuture s can not be explicitly completed (setting its value and status). It doesn't have a mechanism to create stages of processing that are chained together. There is no mechanism to run Future s in parallel and after to combined their results together.
In Java 8 you can use the built-in CompletableFuture:
Future future = CompletableFuture.completedFuture(value);
Apache Commons Lang defines similar implementation that is called ConstantFuture, you can get it by calling:
Future<T> future = ConcurrentUtils.constantFuture(T myValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With