scala - Am I safely mutating in my akka actors or is this not thread safe? -
i little confused if safely mutating mutable maps/queue inside of actor.
can tell me if code thread-safe , correct?
class someactor extends actor { val userq = mutable.queue.empty[user] val tranq = mutable.map.empty[int, transaction] def receive = { case blank1 => if(userq.isempty) userq ++= getnewusers() case blank2 => val companyprofile = { company <- api.getcompany() // future[company] location <- api.getloc() // future[location] } yield companyprofile(company, location) companyprofile.map { cp => tranq += cp.id -> cp.transaction // tranq mutatated here } } }
since mutating tranq futures, safe?
it understanding each actor message handled in serial fashion, although maybe frowned upon can use mutable state this.
i confused if using inside of future call tranq safe or not.
no, code not safe.
while actor processes 1 message @ time, lose guarantee future
s involed. @ point, code inside future
executed on (potentially) different thread , next message might handled actor.
a typical pattern work around issue send message result of future
using pipeto
pattern, so:
import akka.pattern.pipe def receive: receive { case mymsg => myfutureoperation() .map(res => mymsg2(res)) .pipeto(self) case mymsg2(res) => // mutation }
more information using future
s can found in akka's documentation: http://doc.akka.io/docs/akka/2.5/scala/futures.html
Comments
Post a Comment