[2.1 Java] How to Await on an array of futures?

717 views
Skip to first unread message

Chanan Braunstein

unread,
Apr 5, 2013, 2:13:39 PM4/5/13
to play-fr...@googlegroups.com
Hello,

I need to do X amount of work which I will perform inside actors. The actors will respond when they are done. I know how to Await on an actor, but how do you await on an array of actors till they are all done?

Martin Grotzke

unread,
Apr 5, 2013, 3:22:25 PM4/5/13
to play-fr...@googlegroups.com
If you're working with promises you can use Promise.sequence(promises)
which returns a Promise of all results, so that you can finally map on this.

Cheers,
Martin
> --
> You received this message because you are subscribed to the Google
> Groups "play-framework" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to play-framewor...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

signature.asc

stikkos

unread,
Apr 5, 2013, 4:13:04 PM4/5/13
to play-fr...@googlegroups.com
You can use akka.dispatch.Futures.sequence as described on http://doc.akka.io/docs/akka/snapshot/java/futures.html  (under Composing Futures)

Example:

import static akka.dispatch.Futures.sequence;
final ExecutionContext ec = system.dispatcher();
//Some source generating a sequence of Future<Integer>:s
Iterable<Future<Integer>> listOfFutureInts = source;
 
// now we have a Future[Iterable[Integer]]
Future<Iterable<Integer>> futureListOfInts = sequence(listOfFutureInts, ec);
 
// Find the sum of the odd numbers
Future<Long> futureSum = futureListOfInts.map(
  new Mapper<Iterable<Integer>, Long>() {
    public Long apply(Iterable<Integer> ints) {
      long sum = 0;
      for (Integer i : ints)
        sum += i;
      return sum;
    }
  }, ec);
 
futureSum.onSuccess(new PrintResult<Long>(), system.dispatcher());

Chanan Braunstein

unread,
Apr 5, 2013, 4:26:26 PM4/5/13
to play-fr...@googlegroups.com, martin....@googlemail.com
I am close but don't have it right yet. This is what I have so far:

List<Promise<Object>> list = new ArrayList<Promise<Object>>();
Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS));
for(int i = 0; i < message.getNumberOfStudents(); i++) {
InsertTestScore msg = new InsertTestScore(message.getCourseId(), message.getTestId(), String.format("U%d", i + 1), 60 + rnd.nextInt(40));
list.add(Akka.asPromise(Patterns.ask(insertScoreActor, message, timeout)));
}
Promise waitAll = Promise.sequence(list);

The problem is that Promise.sequence is expecting a type of java.lang.Iterable<F.Promise<? extends A>

Skamander

unread,
Apr 5, 2013, 4:30:55 PM4/5/13
to play-fr...@googlegroups.com, martin....@googlemail.com

Chanan Braunstein

unread,
Apr 7, 2013, 2:08:35 PM4/7/13
to play-fr...@googlegroups.com, martin....@googlemail.com
Thanks! That helped!

I noticed this class: play.libs.F.Promise.PromiseActor - Do you happen to know how to use it?
Reply all
Reply to author
Forward
0 new messages