How do Erlang/Akka etc. send messages under the hood? Why doesn't it lead to deadlock?

Viewed 104

Message sending is a useful abstraction, but it seems to be a bit misleading because it is not like letters sent through a post box that are literally moving through the system.

Similarly in Kafka they talk about messages but really it's just reading/writing to a distributed, append-only log.

In Erlang/Akka you actually copy the data rather than 'send it' so how does this work? I was imagining something like Alice sends a message to Bob by

  1. acquiring a lock to Alice's queue (i.e. mailbox)
  2. write the message to the queue
  3. release the lock
  4. do something else Given that you can send a message to anyone how does this not result in a massive deadlock with processes all waiting to message Alice. It seems like it might be useful to have multiple intermediate mailboxes for popular actors so you can write to that and then go do something else faster.
1 Answers

The receiver is not locking its mailbox when it is waiting for a message; only when it checks it, briefly. If there is no matching message, it releases the lock and goes to sleep, then gets woken up when new messages arrive. Likewise, senders also only need to aquire the lock while inserting the message. There is never any deadlock situation on this level.

Processes may still get deadlocked because of logical errors where both are expecting a message from the other at the same time, but that's a different matter, and the message passing style makes it less likely to end up in that situation, because there is no lock management to screw up on the user level.

As you mention, yes, it is useful to have intermediate mailboxes to reduce contention (a sender can add to the incoming side of the mailbox while a receiver is holding a lock to scan through the messages arrived so far), and that optimization is handled for you under the hood by the Erlang VM.

Related