How does akka know which specific message reply is associated with the correct future?

actor, akka, future

Solution

Every `Actor` has a path. From inside of the `Actor`, you could say:

context.path

From outside an `Actor`, if you had an `ActorRef`, you could just say:

ref.path

This path if the address of that individual actor instance, and it's how I believe the internal routing system routes messages to the mailboxes for actors instances. When you are outside of an `Actor`, like you are when you are looping and sending messages in your example, when you use `ask` (the `?`), a temporary `Actor` instance is started up so that when the `Actor` that received the message needs to response, it has a path to respond to. This is probably a bit of an oversimplification, and it might not be the level of detail that you are looking for, so I apologize if I missed the gist of your question.

Also, the `sender` var in an `Actor` is an `ActorRef`, thus it has a path so you can route back to it.

When a `Future` is created, akka creates a temporary (and addressable) `Actor` that is basically servicing that `Future`. When that temporary `Actor` sends to another `Actor`, its `ActorRef` is transmitted as the sender. When the receiving actor is processing that specific message, the sender `var` is set to the `ActorRef` for that temp actor, meaning that you have an address to respond to. Even if you decide to hold on to that sender for later, you still have an address to send back to and eventually complete the `Future` that the temporary actor is servicing. The point is, as long as you have an `ActorRef`, whether it's a request or a response, all it's doing is routing a message to the path for that `ActorRef`.

`Ask (?)` and `tell (!)` really aren't much different. `Ask` is basically a `tell` where the sender is expecting the receiver to `tell` a message back to it.

Problem

Lets say I ask (?) the same actor for two responses. It stores the sender for later. Later, it gets messages back to go to the senders. We get the right sender (the one hashed to the message) but how does Akka know which message the response is for? Is there something in the ActorRef that indicates which message each response is for? Is it the 'channel'? I'd like to understand the underlying technology better. I'll try to read the source at the same time but I think this is a really good question. Code example: ``` class TestActor [...] def onReceive = { case r: MessageToGoOut ⇒ messageId += 1 val requestId = clientConnectionId + messageId senders += (requestId -> sender) //store sender for later anotherActor ! WrappedUpMessage(requestId, MessageOut)) case m: MessageToGoBackToSender ⇒ val requestId = m.requestId senders.get(requestId) map { client ⇒ client ! Response(m.message) senders -= requestId } } val futures = for(i <- 1 to 100) yield testActor ? new MessageToGoOut ("HEYO!" + i) ``` Now how does akka ensure the messages get back to the right actor??

Original source