How to create a completed future in java

JavaFuture

Java Problem Overview


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();
    }
}

Java Solutions


Solution 1 - Java

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

 Future future = CompletableFuture.completedFuture(value);

Solution 2 - Java

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

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

Solution 3 - Java

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

Solution 4 - Java

FutureTask<String> ft = new FutureTask<>(() -> "foo");
ft.run();

System.out.println(ft.get());

will print out "foo";

You can also have a Future that throws an exception when get() is called:

FutureTask<String> ft = new FutureTask<>(() -> {throw new RuntimeException("exception!");});
ft.run();

Solution 5 - Java

I found a very similar class to yours in the Java rt.jar

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

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

Solution 6 - Java

In Java 6 you can use the following:

Promise<T> p = new Promise<T>();
p.resolve(value);
return p.getFuture();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJake WalshView Question on Stackoverflow
Solution 1 - JavaAndrejsView Answer on Stackoverflow
Solution 2 - JavahoazView Answer on Stackoverflow
Solution 3 - JavaLouis WassermanView Answer on Stackoverflow
Solution 4 - JavaDaveView Answer on Stackoverflow
Solution 5 - JavaAlex WordenView Answer on Stackoverflow
Solution 6 - JavaAlexVView Answer on Stackoverflow