5

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);  
        }
    }
le-doude
  • 3,345
  • 2
  • 25
  • 55

1 Answers1

5

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 :)

Viktor Klang
  • 26,479
  • 7
  • 51
  • 68
  • I have tried, it's just that Promise is extending j.u.c.Future ... so I had hope. – le-doude Aug 14 '13 at 11:54
  • That direction is very simple; Promise/Future is strictly more powerful/flexible than j.u.c.Future – Viktor Klang Aug 14 '13 at 12:15
  • If only Java's Future supported the concept if a completion listener (observer) then you be able to create a bridge between Java's Future and Scala's Future via a Promise but alas such things do not exist... – cmbaxter Aug 14 '13 at 12:27
  • Fortunately my dear friend Doug might be of assistance there in the future (excuse my pun): http://download.java.net/lambda/b103/docs/api/java/util/concurrent/CompletableFuture.html – Viktor Klang Aug 14 '13 at 12:39
  • Wow! Now that's what I'm talking about :) – cmbaxter Aug 14 '13 at 13:11
  • @cmbaxter I have a scenario where a java api provides a callback, but I can't figure out how to convert to a promise. I posted the question at http://stackoverflow.com/questions/32582411/how-to-convert-callback-to-a-promise. Can you help out? – Can't Tell Sep 15 '15 at 10:31