[erlang-questions] funs and code loading

Fred Hebert mononcqc@REDACTED
Tue Jun 3 16:56:02 CEST 2014

On 06/03, Dániel Szoboszlay wrote:
> My question is why’s the difference?
> [...]
> Could someone explain to me what is the VM doing here and why?

The distinction here comes back to the difference between local calls,
and fully qualified function calls, vis. code loading.

It's a process I have tried to describe at
including this image:

The gist of it is that local calls (calling a function without a module)
always keeps using the current code used by a process at the time it was
being called. Fully qualified calls are calls made through a module
(Mod:Fun(Args), apply(Mod, Fun, [Args]), and so on) will always use the
latest version of a module that is loaded in the VM.

If you load a third version of a module while a process still runs with
the first one, that process gets killed by the VM, which assumes it was
an orphan process without a supervisor or a way to upgrade itself. If
nobody runs the oldest version, it is simply dropped and the newest
ones are kept instead.

So what you see with anonymous functions here is the same mechanism,
just repeated in a different way.

An inline anonymous function like fun() -> do_something_local() end or
fun my_local_stuff/2 will be declared and running the 'old' version of
the code, and pointing to the old version of the code. This, like any
other process running or holding old code, will need to be killed if it
can't drop that value before a second code reloading is done.

A fully qualified fun (fun Mod:Fun/Arity) will however be a fully
qualified function that doesn't refer to any specific code version and
will be reloadable.

This may have an important impact when deciding whether to use
spawn(fun() -> my_loop(), log(whatever) end) versus spawn(?MODULE,
my_loop, []), for example.

Hopefully that helps.


More information about the erlang-questions mailing list