Surender Raja
Surender Raja

Reputation: 3609

Akka actor is processing the second message before processing the first message

I am learning and understanding Akka actor model with some basic examples.

I created two instances for a same Actor (i.e) "helloworld1" and "helloworld2" and sending messages to that Actor. The first message is sent by instance "helloworld1" and second message is sent by "helloworld2" .

When i run the below code i get output as below

Yes you made it Hi helloworld2
Yes you made it Hi helloworld1

My question is why is it the 2nd message is processed at first? I was expecting the output as below because the first message is sent by helloworld1

Yes you made it Hi helloworld1
Yes you made it Hi helloworld2

Code for ActorApp:

import akka.actor.{ActorSystem, Props}

object ActorApp {

 def main(args :Array[String]) ={

 val system = ActorSystem("SimpleActorSystem")

 val actorObj1 = system.actorOf(Props[HelloWorld],"helloworld1")
 actorObj1 ! "Hi helloworld1"//first message sent

 val actorObj2 =system.actorOf(Props[HelloWorld],"helloworld2")
 actorObj2 ! "Hi helloworld2"//second message sent

}

}

Code for Actor:

import akka.actor.Actor

class HelloWorld extends Actor {

 def receive = {

case dataStr:String => println("Yes you made it "+dataStr)

}

}

Upvotes: 1

Views: 188

Answers (1)

alextsc
alextsc

Reputation: 1368

Akka does not guarantee that messages are delivered in the order they are sent globally. It guarantees the following:

  • at-most-once delivery (i.e. no guaranteed delivery, messages may be dropped)
  • message ordering per sender–receiver pair

So you see, the ordering is only guaranteed for any given sender-receiver pair. If you send multiple messages from "helloworld1" they will be received in the order you sent them (however messages from other sources may come in between).

See the documentation for an in-depth explanation.

Upvotes: 1

Related Questions