memory-leakselixirworkererlang-otpets

Will ets table release memory after recreating with the same name?


I have genserver that aggregates events:

  def init(opts) do
    cache = :ets.new(:events_cache, [:set])
    {:ok, cache}
  end

  def handle_info(:autoflush, cache) do
    Logger.debug(fn -> "#{:ets.info(cache)[:size]} events was aggregated. Sending to transport..." end)
    Events.emit(:ets.tab2list(cache))
    Process.send_after(self(), :autoflush, @flush_after)
    {:noreply, :ets.new(:events_cache, [:set])}
  end

  def handle_cast({:add_event, event}, cache) do
    :ets.insert(cache, {event})
    {:noreply, cache}
  end

In init I create ets table. Add values in cast and flush data to external call in info cleaning memory of ets table(as I think).

Questions:

  1. Is this implementation prone to memory leak? Is old ets table garbage collected?
  2. Aside question: Does this implementation look sanely at all?

Solution

  • EDIT (July 18th 2024) Just answering the question, if the memory is collected, I assume it should be because the ETS table is linked to the process and If that process is terminated, the ETS table must be removed.

    Provide a name that is correct and could be in use if you don't believe in the proper cleaning of the ETS, but it's not a valid option if more than one server is created (unnamed servers).