How do I do Future.firstCompletedOf in Java?

78 views
Skip to first unread message

Craig O

unread,
Sep 25, 2014, 11:38:36 PM9/25/14
to play-fr...@googlegroups.com
I've asked this on stackoverflow (http://stackoverflow.com/questions/25995509/how-to-add-a-timeout-to-f-promise-promise-and-or-f-promise-sequence) a couple of days ago, but haven't received an answer yet.

I got it down to :

my question can be simplified to "how do I set a timeout on a controller method that returns a Promise", yet another place where the Java documentation seems inferior to the Scala docs.. The Scala docs show how to do it, but the Java ones don't. How do I do Future.firstCompletedOf in Java? And why, oh why does the java docs suck so much?

It's a real pain to read the java docs, then, much later realise there is considerably more info in the scala ones, and no way to tell how to do the scala difference in java.  I find this happening over and over..

I've tried poking around in the Future api, and can see the scala class with it (scala.concurrent.Future), but I'm very new to scala, and don't know how (if at all), I can call this method from Java?


Megazord

unread,
Sep 26, 2014, 12:57:46 AM9/26/14
to play-fr...@googlegroups.com
Hi Craig,

Since Play uses Akka, you could use it too (btw, most of the time you need to use futures and actors, you will be more well served by Akka docs). Here is an simple example of how to do that in Java:

import play.libs.Akka;
import akka.dispatch.Futures;
import akka.dispatch.MessageDispatcher;
import scala.concurrent.Future;
import scala.concurrent.ExecutionContext;

Future<User> future1 = null;
Future<User> future2 = null;
Future<User> future3 = null;
List<Future<User>> futures = Arrays.asList(future1, future2, future3);

ExecutionContext executor = Akka.system().dispatchers().lookup("your-dispacher-name");
// Or to get the default dispacher
// ExecutionContext executor = Akka.system().dispatcher();
   
Futures.firstCompletedOf(futures, executor).map( ... );


HTH

Craig O

unread,
Sep 26, 2014, 1:05:02 AM9/26/14
to play-fr...@googlegroups.com
Ahh, thanks!  Futures.firstCompletedOf in Java and Future.firstCompletedOf in Scala.  Would be nice if the typesafe crew could put this in the Java version of the docs, would have saved me a lot of time.  Interestingly, I can't find Futures.firstCompletedOf in a google search unless I quote it..

Thanks so much Megazord, it certainly does help!
Reply all
Reply to author
Forward
0 new messages