113

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();
    }
}
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Jake Walsh
  • 3,669
  • 5
  • 22
  • 28
  • 1
    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? – assylias Dec 13 '12 at 18:58
  • 1
    I suspect none exists because I have never seen a reason to have one. Perhaps you could explain what you are trying to do? – Peter Lawrey Dec 13 '12 at 18:59
  • 1
    @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. – Cubic Dec 13 '12 at 19:02
  • 13
    Unit tests would be a perfectly good reason to want this -- a mocked service returning a future with test values. – Louis Wasserman Dec 13 '12 at 19:43
  • 3
    @Cubic. How about if you had a method that accepts a Callable 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)](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-) took a Callable as parameter instead and decided to run it in the executing thread, wouldn't the implementation need to create his own Future then? – Martin Andersson Apr 05 '14 at 08:43
  • 3
    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. – Alex Worden Jun 25 '15 at 19:39

6 Answers6

240

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

 Future future = CompletableFuture.completedFuture(value);
Andrejs
  • 26,885
  • 12
  • 107
  • 96
  • 1
    This would give you a completed future. Instead use new CompletableFuture(). – zafar142003 Mar 08 '18 at 18:10
  • 14
    @zafar142003 OP asked for a completed future, no? – Andrejs Mar 10 '18 at 09:31
  • 1
    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. – zafar142003 Mar 10 '18 at 16:37
  • 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. – nathanfranke Sep 28 '20 at 10:17
  • Note that `CompletableFuture` isn't compatible with `ListenableFuture`; if you need a listener, you might consider a different implementation based on `ListenableFuture`. – Eric Dand Aug 24 '23 at 19:49
70

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

Future<T> future = ConcurrentUtils.constantFuture(T myValue);
hoaz
  • 9,883
  • 4
  • 42
  • 53
44

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

reevesy
  • 3,452
  • 1
  • 26
  • 23
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
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();
Dave
  • 13,518
  • 7
  • 42
  • 51
-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.

Alex Worden
  • 3,374
  • 6
  • 34
  • 34
  • 3
    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. – James Kingsbery Apr 01 '19 at 16:58
-6

In Java 6 you can use the following:

Promise<T> p = new Promise<T>();
p.resolve(value);
return p.getFuture();
AlexV
  • 544
  • 9
  • 19
  • 3
    I don't think that's in the Java core libraries. What external dependency does it use? – Jorn Oct 03 '16 at 07:18