Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From java.util.concurrent.Future<T> to play.libs.F.Promise<T>: How to do that in Java?

I am using play framework to implement a REST API service.

In one function I am using a java async library to talk to another service and it returns a java.util.concurrent.Future<T> that I map (using Guava Futures.transform(~)) into a java.util.concurrent.Future<play.mvc.Result>.

Now, how do I make it a play.libs.F.Promise<Result> so that I can make an AsyncResult?

I found play.libs.Akka.asPromise(scala.concurrent.Future<T> future) but I cannot find a way (in Java) to get a scala future from a java one.

EDIT TEMPORARY SOLUTION: Here is what I am using right now:

Future<T> future = asyncGetTheFuture();
Promise<T> promise = Akka.future(new JFutureToPromise<T>(tempFuture));

with

    class JFutureToPromise<T> implements Callable<T> {
        final Future<T> future;
        final long time;
        final TimeUnit unit;

        private JFutureToPromise(Future<T> future, long time, TimeUnit unit) {
            this.future = future;
            this.time = time;
            this.unit = unit;
        }

        private JFutureToPromise(Future<T> future) {
            this(future, 10L, TimeUnit.SECONDS);
        }

        @Override
        public T call() throws Exception {
            return future.get(time, unit);  
        }
    }
like image 898
le-doude Avatar asked Aug 14 '13 11:08

le-doude


People also ask

What is 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 promise in play framework?

promise(F.Function0<A> function) Create a Promise which will be redeemed with the result of a given function. static <A> F.Promise<A> promise(F.Function0<A> function, scala.concurrent.ExecutionContext ec) Create a Promise which will be redeemed with the result of a given Function0.

What is the usage of Future class?

Simply put, the Future class represents a future result of an asynchronous computation. This result will eventually appear in the Future after the processing is complete. Let's see how to write methods that create and return a Future instance.


1 Answers

There is no way to non-blockingly/non-pollingly transform an arbitrary j.u.c.Future into an async Future/Promise. Try it and see for yourself :)

like image 105
Viktor Klang Avatar answered Sep 21 '22 11:09

Viktor Klang