Search code examples
concurrencyakkaactorsynchronized

Synchronized, wait and notify in Akka


I'd like to ask you a thing. I have one "Rec" actor and more "Sen actors". The first one has a list of messages that must be forwarded and the senders are actors that keep sending messages to Receiver.

Something like this:

class Rec (frw: Actor) extends Actor
{
    val myList = Nil;
    def act =
    {
            case "Start" => while(true) {/*Extract the first number and send it to frw*/} //I must use a new actor if I want to keep reading messages
            case i => myList+=i; //Should i use a "synchronize" here (i'm extracting elements with the other actor after all)?
    }
}

class Sen (rcv: Actor) extends Actor
{
    var i=100;
    def act =
    {
            case "Start" => while(i>0) {i+=1; rcv ! i;}
    }
}

My problem is that Rec must forward just one message at the time, so it must save all the messages in a list. Is there a way to improve the Rec actor? I don't like the while(true), but i can't extract the first number whenever i receive a message (messages could stay in too long in the list). Should i use synchronized/wait/notify or is there something better for Akka? Thank you and sorry for my bad english.


Solution

  • According to your code you do not need the Rec actor at all. You will achieve the same result if you send messages from Sen to frw directly.

    You have to rememeber that Akka actors process messages sequentially one after another. So all your messages from Sen will arrive to frw one message at the time even if you send them directly from Sen to frw.