RayRoestenburg/akka-in-action

Chapter 5 Futures - the sender reference of an actor...

weicheng113 opened this issue · 2 comments

Hi,

I am having difficulty in understanding "The sender reference of an actor needs to be captured into a value before it can be safely used" at the summary of Chapter 5 Futures. Can you please explain more on "needs to be captured into a value"? Thanks.

What i currently understand is we can use
a. pipe(a future) to sender()
b. or methods from Future. for example, a future.onComplete(...) { sender() ! a successful value or a failure}

Thanks in advance,
Cheng

Hi Cheng,

@weicheng113 The sender() is a method. It is not a value (It can't be, since every message is sent by possibly a different sender). It changes along with the context of the actor, which is the context in which it is receiving a message from a sender. if you call sender() outside of the normal receive call, for instance on a onComplete, you are basically calling sender() from a different thread. The sender() method must only be called from the thread that the actor is currently running on, receiving that specific message. If you call it from another thread, you might get the sender of a totally different message!

Now, if you are on the 'current thread' where the actor is receiving the message, and where it is valid to call sender() , you could do val currentSender = sender(). The value currentSender then has the valid sender reference. You can safely pass the currentSender to another thread, since you have already correctly read the sender on the thread that the actor was receiving the message on.

Hope that explains it.

Use the pipe(future) to sender() directly from the actor receive method and you will always be safe.

Thanks a lot for the detailed explanation, Raymond. I understand it now.