How to create a completed future in java
Asked Answered
I

6

116

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();
    }
}
Illaudable answered 13/12, 2012 at 18:56 Comment(6)
The best way is to not create one! ;-) Why do you need to implement a Future? Can't you use existing objects that return a future instead?Dominquedominquez
I suspect none exists because I have never seen a reason to have one. Perhaps you could explain what you are trying to do?Diao
@PeterLawrey I suppose he needs it for some API that for some twisted reason wants to work with futures even though it really only needs its values. Or he needs it for mocking. At least that's the only reasons I can imagine.Erlandson
Unit tests would be a perfectly good reason to want this -- a mocked service returning a future with test values.Nanice
@Cubic. How about if you had a method that accepts a Callable<T> and who may or may not run the job asynchronously dependent on available resources or other factors such as options that has already been provided way earlier? Imagine if Executor.execute(Runnable) took a Callable<T> as parameter instead and decided to run it in the executing thread, wouldn't the implementation need to create his own Future<T> then?Cruzeiro
I have the same need and can explain... The code I'm writing expects a list of Futures representing results of queries that are all obviously executed concurrently. However, in each case, the query result may be cached, and when it is, my code returns a CompletedFuture of the cached result. This gives a clean abstraction and separation of concerns.Aqueduct
T
71

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

Future<T> future = ConcurrentUtils.constantFuture(T myValue);
Tica answered 13/12, 2012 at 19:2 Comment(1)
See Andrejs' answer below, it might be more of what you're looking forTaboo
V
248

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

 Future future = CompletableFuture.completedFuture(value);
Veii answered 17/2, 2015 at 14:37 Comment(5)
This would give you a completed future. Instead use new CompletableFuture().Araliaceous
@Araliaceous OP asked for a completed future, no?Veii
judging by the class in the question details (in 2012), I think the OP wanted a 'CompletableFuture' implementation. But I guess, this is now a moot point.Araliaceous
Judging by the class in the question details, it looks like OP wanted a Future with an immediate value. See that isDone always returns true. Therefore, this is an excellent answer.Taboo
Note that CompletableFuture isn't compatible with ListenableFuture; if you need a listener, you might consider a different implementation based on ListenableFuture.Akel
T
71

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

Future<T> future = ConcurrentUtils.constantFuture(T myValue);
Tica answered 13/12, 2012 at 19:2 Comment(1)
See Andrejs' answer below, it might be more of what you're looking forTaboo
N
44

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

Nanice answered 13/12, 2012 at 19:25 Comment(0)
C
5
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();
Citral answered 10/9, 2019 at 18:58 Comment(0)
A
-3

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.

Aqueduct answered 25/6, 2015 at 19:37 Comment(1)
Generally, using anything in the com.sun.* package is not a great idea. Those classes are generally considered an internal implementation detail, and are liable to change across versions of Java.Merridie
M
-7

In Java 6 you can use the following:

Promise<T> p = new Promise<T>();
p.resolve(value);
return p.getFuture();
Mesoderm answered 22/8, 2016 at 6:7 Comment(1)
I don't think that's in the Java core libraries. What external dependency does it use?Hurtle

© 2022 - 2024 — McMap. All rights reserved.