securecurve
securecurve

Reputation: 5807

How Erlang atoms can be garbage collected

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'm fairly new to Erlang, and my question is: How the atoms can be garbage collected? And if not possible, how to minimize that effect?

Upvotes: 6

Views: 2088

Answers (3)

Drey
Drey

Reputation: 59

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.

Upvotes: 1

fenollp
fenollp

Reputation: 2496

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.

Upvotes: 5

Chiron
Chiron

Reputation: 20245

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!

Upvotes: 13

Related Questions