[erlang-questions] funs and code loading
Tue Jun 3 11:09:11 CEST 2014
There’s some strange behaviour with local funs and code loading in the VM that I don’t understand.
If I create a local fun in a process (e.g. something like F = fun () -> … end and not like F = fun foo:bar/1) the fun will be bound to my process (erlang:fun_info(F, pid) will return the creating process), and also to the current code version of the module where the fun was defined. If I load a new version of the module, the fun will point to old code. If I load an other new version of the module, the fun will no longer has its code in memory.
At this point:
The process that created the fun is killed (I believe even if it cannot access the fun anymore, but it’s not yet garbage collected).
If I sent the fun to an other process, it is killed as well.
However, if I stored the fun in an ets table, the table survives the code loading. I can even retrieve the fun in a third process, call erlang:fun_info/2 on the fun there etc. If I try to invoke the fun however I get a badfun error.
My question is why’s the difference? This is very confusing: some processes having the fun are killed, some others are not. On the surface the two funs look equal, but are they implemented in a different way somehow? I could imagine that the “killing fun” stores an actual pointer to the code (on the emulator level) for efficiency reasons, while the ets version stores only the hash of the module or something similar. But how does the fun in the process that retrieved the value from the ets table look like than?
And if a process can have a fun that has no corresponding code why are processes killed at all (assuming they are not executing the old code at the moment)? Why aren’t their invokable funs simply replaced with this non-invokable fun? (If I’m not mistaken funs are stored in an off-heap memory area, so you wouldn’t even have to search the process’ entire heap to find them.)
Could someone explain to me what is the VM doing here and why?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the erlang-questions