Akka Actor Communication
In Akka, actors communicate to each other by sending and receiving messages.
Akka Actor Send Messages
Akka provides two predefined methods tell() and ask() for message exchange. An actor can send messages to another Actor through these following methods.
1) Akka Actor tell() Method
It is used to send a message asynchronously. It does not wait and block thread for a message. It works on “fire-forget” approach. You can also use ! (bang) exclamation mark to send message. This is the preferred way of sending messages. It gives the best concurrency and scalability characteristics.
If this method is invoked from within an Actor, the sending actor reference will be implicitly passed along with the message.
If this method is invoked from an instance that is not an Actor, the sender will be deadLetters actor reference by default.
Actor tell() Method Example
Output:
Message received: Hello from - RootActor sender:Actor[akka://ActorSystem/deadLetters] // ActorRef refers to deadLetters Message received: Hello from - RootActor sender:Actor[akka://ActorSystem/deadLetters] // ActorRef refers to deadLetters
Akka Actor tell() Method Example2
Output:
Message received: Hello from - RootActor Sender: Actor[akka://ActorSystem/deadLetters]// Called from outside Actor Message received: Hello from - ChildActor Sender: Actor[akka://ActorSystem/user/RootActor#1451914889]// Called from within Actor
2) Akka Actor ask Method
In akka, ask is a pattern and involves Actors as well as Futures. Ask is used to sends a message asynchronously and it returns a Future which represents a possible reply. If the actor does not reply and complete the future, it will expire after the timeout period. After timeout period, it throws an TimeoutException. You can use either ? (question mark) or ask() to send message.
You should always prefer tell method for performance and ask method, if you want response.
Akka Actor ask Method Example
Output:
Message recieved: Hello Exception in thread "main" java.util.concurrent.TimeoutException: Futures timed out after [2 seconds]
Akka Actor ask() Method Example2
Output:
Message received: Hello from outside actor instance Replaying Message received: Hello, I got your message.
Akka Actor Ask Method Example3
Output:
Message received: Hello from outside actor instance Exception in thread "main" java.util.concurrent.TimeoutException: Futures timed out after [2 seconds]