Does Future.sequence preserve the order?

1,759 views
Skip to first unread message

Michi

unread,
Jul 30, 2012, 11:16:26 AM7/30/12
to scala...@googlegroups.com
Hi,

is it guaranteed that Future.sequence always preserves the order? In the following example I create ten actors which have an ID from 0 to 9. I want to create a list of actors and there IDs:

import akka.actor.{ActorRef, Props, Actor, ActorSystem}
import akka.dispatch.{Future, Await}
import akka.pattern.ask
import akka.util.Timeout
import akka.util.duration._

case object RequestIdMessage

case class IdMessage(id: String)

object Main {
  def main(args: Array[String]) {
    val system = ActorSystem("Main")
    // create a list of actors
    val actors = (0 until 10) map (i => system.actorOf(Props(new MyActor(i.toString))))
    implicit val timeout = Timeout(5 seconds)
    // create a list of futures
    val listOfFutures = actors map (((actor: ActorRef) => (actor ? RequestIdMessage).mapTo[IdMessage]))
    implicit val ec = system.dispatcher
    val futureList = Future.sequence(listOfFutures)
    val result = Await.result(futureList, timeout.duration)
    println(actors.zip(result))
  }
}

class MyActor(id: String) extends Actor {
  def receive = {
    case RequestIdMessage => sender ! IdMessage(id)
  }
}

Apparently Future.sequence does preserve the order, but the API documentation does not state this anywhere. Is it guaranteed that Future.sequence will always preserve the order in the future? If not, how would be the best way to write the program above?

Thanks,
Michael

pagoda_5b

unread,
Jul 30, 2012, 11:32:32 AM7/30/12
to scala...@googlegroups.com
Is this correct?

class MyActor(id: String) extends Actor {
  def receive = {
    case RequestIdMessage => sender ! (self, IdMessage(id))
  }

and then println(results)?

Bye,
Ivano

Roland Kuhn

unread,
Jul 30, 2012, 2:58:59 PM7/30/12
to Michi, scala...@googlegroups.com
Hi Michi,

yes, if you pass in a sequence, you'll get out a sequence; everything else I'd call a bug, given the name of the method ;-) (which would inspire me to try it out with a Set if I were in front of a computer)


Regards,

Roland Kuhn
Typesafe — The software stack for applications that scale
twitter: @rolandkuhn

Josh Suereth

unread,
Jul 30, 2012, 3:18:04 PM7/30/12
to Michi, scala...@googlegroups.com
Note: The order of the sequence is maintained but the *order of processing* the sequence elements does not have to be sequential.  That may be obvious, but it's worth noting.  That's more of a note to make on "traverse" which is the more general form of "sequence".

- Josh
Reply all
Reply to author
Forward
0 new messages