scala - Akka Future Respose to a Sender -
i came across following sip:
http://docs.scala-lang.org/sips/pending/spores.html
as reading through, came across example:
def receive = { case request(data) => future { val result = transform(data) sender ! response(result) } }
there description below in article:
> capturing sender in above example problematic, since not return stable value. possible future’s body > executed @ time when actor has started processing next > request message originating different actor. > result, response message of future might sent > wrong receiver.
i not understand line "capturing sender in above example problematic...." isn't case in each request actor (request(data)) create future block?
the creating of future block synchronous mean sender reference known @ time. execution of future block somehow scheduled happen @ later point in time.
is understanding correct?
def receive = { case request(data) => future { val result = transform(data) sender ! response(result) } }
imagine line sender ! response(result)
executed after 300 ms, @ same time enclosing actor handling message, let's call m
. because sender def, not val, it's evaluated every time it's used. means, inside future you've got sender of m
message! you've responded not sender of original message created future
, other guy. mitigate problem need close on value of sender() def @ time of creation of future
. compare original code this:
def receive = { case request(data) => val client = sender() future { val result = transform(data) client ! response(result) } }
you have remembered original sender, correct.
it's of utmost importance never execute methods depend on time (like sender
) or change actor's state in asynchronous manner. if need change actor's state in response asynchronous computation, should send message future
block.
Comments
Post a Comment