Search code examples
erlangelixirbeam

What is the Synchronous Call Trick/Ref Trick in BEAM


We were recently reading the BEAM book as part of our reading group. In Chapter 7 there is an allusion to the ref trick/Synchronous Call Trick in Erlang.

Unfortunately, the book is incomplete and after discussion we were unable to figure out the ref trick was.


Solution

  • When performing a receive, the BEAM VM scans the mailbox in order to find the first suitable (matching) message, and blocks the process if it does not find any.
    The 'trick' is that, since it's impossible for a new reference to be in the mailbox before it was created, there's no need to scan the whole mailbox when receive {Reference, Term}, only from the point where Reference was created.

    That's the meaning of the following phrase:
    The compiler recognizes code that uses a newly created reference (ref) in a receive (see [ref_trick_code]), and emits code to avoid the long inbox scan since the new ref can not already be in the inbox.