Is there a way to tell if an atom exists?

Is there a way to tell if an atom already exists? If I’m thinking about this correctly, if you already “have” an atom somewhere in your code, then it must already exist because it was parsed. In other words, if you had something like is_existing_atom(:foo), then the atom :foo must already exist because it was summoned into existence when that code got parsed – is that right?

For context, the reason I started thinking about this was while working on a long-running job processor that spins up a lot of processes over time. I realized that if I provide a name to these processes (i.e. a name provided to the Agent or Genserver, or even more generically a name registered via Process.register/2), then I might get into trouble because atoms are not garbage collected: if my app ran long enough and processed enough jobs, then the VM might crash given enough unique process names. I think that’s a valid concern, but someone correct me if I’m wrong.

To avoid getting into VM trouble down the road by registering too many atoms (and I realize I may not hit that limit in the confines of normal operation), one solution might be to store a map that would connect a string ID to a pid (e.g. in ETS). The advantage would be I could easily delete keys that were no longer relevant; the disadvantages would be the necessity to manage an ETS table and deal with the cleanup of keys that point to dead pids.

FYI: The closest related function here is String.to_existing_atom/1 which I will include for searches.

You can use arbitrary keys with Registry.


You can dump the atom table. Do Atom.to_term so you can compare against a string. Not the best solution I agree

Thanks! I didn’t realize that. Because Registry uses ETS internally, do you know of any benefits from using it over manually tracking this in ETS? I suppose using Registry is more idiomatic and it would deal with partitions better.

Not needing to write the needed code it in the first place :smiley:

Also, if the process crashes, it is automatically removed from the Registry (aka: it’s already monitored for you).

Ah, that’s huge. Yes, thanks for pointing that out!

Of course I meant Atom.to_string