Search code examples
erlangerlang-supervisor

Are Erlang references garbage collected?


I want to dynamically add children to a simple_one_for_one supervisor. For that, I am thinking of creating a child identifier using make_ref() and keep the ref in a map. Once the child terminates, the ref will be removed from the map. In this case will the reference by garbage collected?


Solution

  • You don't reference children of simple_one_for_one supervisors via a child_id(). These supervisors have exactly one child_spec(), and all of their children use that same spec, which means the child_id() in the spec is ignored. The children are instead referenced by their pid. So the start_child/2 function doesn't take a child_spec() (nor a child_id()), only an argument list, and terminate_child/2 takes the pid() instead of a child_id(). So you don't have to generate references at all.

    But, to answer your question: yes, references are garbage collected. All Erlang data types are garbage collected. There are a few caveats if you would really want to dig down into the details, but nothing to really worry about:

    • All atoms are added to an atom table, which is not garbage collected. That means atoms are garbage collected from a process' stack and heap, but even if you remove all references to one specific atom from every process and every ETS table, it would still stay in the atom table.
    • Binaries are garbage collected, but they are shared across processes. The memory used for storing the binary is therefore only reclaimed once the binary is no longer used in any of the processes.
    • When writing NIF-s (natively implemented functions, written in C) you will see that certain types are allocated as reference counted objects by the VM. It is the NIF's duty to maintain the reference counters for these objects, but once they are handed over to the Erlang code, the garbage collector will take care of them too.