Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a completed future in java

Tags:

java

future

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();     } } 
like image 948
Jake Walsh Avatar asked Dec 13 '12 18:12

Jake Walsh


People also ask

How is Future implemented in Java?

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.

What is a Future in Java?

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.

What is the difference between Future and CompletableFuture?

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.

What are the drawbacks of Future interface in Java?

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.


2 Answers

In Java 8 you can use the built-in CompletableFuture:

 Future future = CompletableFuture.completedFuture(value); 
like image 138
Andrejs Avatar answered Sep 28 '22 12:09

Andrejs


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

Future<T> future = ConcurrentUtils.constantFuture(T myValue); 
like image 38
hoaz Avatar answered Sep 28 '22 12:09

hoaz