How Erlang atoms can be garbage collected

前端 未结 3 865
一整个雨季
一整个雨季 2020-12-20 21:17

It is said that atoms are not garbage collected. Once you’ve created an atom, it remains in the atom table, which might cause memory leakage at the end of the day!

I

相关标签:
3条回答
  • 2020-12-20 21:24

    From learn you some Erlang:

    Atoms are really nice and a great way to send messages or represent constants. However there are pitfalls to using atoms for too many things: an atom is referred to in an "atom table" which consumes memory (4 bytes/atom in a 32-bit system, 8 bytes/atom in a 64-bit system). The atom table is not garbage collected, and so atoms will accumulate until the system tips over, either from memory usage or because 1048577 atoms were declared.

    This means atoms should not be generated dynamically for whatever reason; if your system has to be reliable and user input lets someone crash it at will by telling it to create atoms, you're in serious trouble. Atoms should be seen as tools for the developer because honestly, it's what they are.

    0 讨论(0)
  • 2020-12-20 21:32

    While I'm not sure atoms are garbage-collected, you can easily do without worrying whether you will blow up the system's memory. As @Chiron said, as long as all your atoms are known at compile time you should be ok.

    What if I really need to use list_to_atom/1 somehow? Well, you may be able to twist your issue using this kind of function:

    atom("apple") -> apple;
    atom("orange") -> orange;
    atom("banana") -> banana.
    

    One other workaround is list_to_existing_atom/1

    But the VM can still eat more and more RAM: other connected Erlang nodes may register atoms globally, that is allocate atoms at run time.

    0 讨论(0)
  • 2020-12-20 21:47

    Atoms aren't issue unless you are creating them dynamically. If you did that, then you are on your way to crash an Erlang system.

    How to create Atoms dynamically? For example calling list_to_atom function inside a loop.

    If you are interested in Erlang garbage collection, then read this paper by Joe Armstrong: One Pass Real-Time Generational Mark-Sweep Garbage Collection (1995).

    Always keep in mind: Don't create Atoms dynamically!
    Well sometimes you might need to create an Atom dynamically BUT don't over use it!

    0 讨论(0)
提交回复
热议问题