How to create a complete future in java

What is the best way to build a complete future in Java? I performed my own CompletedFuture below, but was hoping something similar already existed.

 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(); } } 
+67
java future
Dec 13 '12 at 18:56
source share
6 answers

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

 Future<T> future = ConcurrentUtils.constantFuture(T myValue); 
+56
Dec 13
source share

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

  Future future = CompletableFuture.completedFuture(value); 
+165
Feb 17 '15 at 2:37
source share

Guava defines Futures.immediateFuture(value) , which does the job.

+36
Dec 13 '12 at 19:25
source share
 FutureTask<String> ft = new FutureTask<>(() -> "foo"); ft.run(); System.out.println(ft.get()); 

will output "foo";

You may also have Future, which throws an exception when calling get ():

 FutureTask<String> ft = new FutureTask<>(() -> {throw new RuntimeException("exception!");}); ft.run(); 
0
Sep 10 '19 at 18:58
source share

I found a very similar class for your in Java rt.jar

com.sun.xml.internal.ws.util.CompletedFuture

It also allows you to specify an exception that can be thrown when the get () method is called. Just set it to null if you don't want to throw an exception.

-3
Jun 25 '15 at 19:37
source share

In Java 6, you can use the following:

 Promise<T> p = new Promise<T>(); p.resolve(value); return p.getFuture(); 
-6
Aug 22 '16 at 6:07
source share



All Articles