Decrementing a Binary Reference Count

I have read that when a process is done with a binary (it doesn’t bind it to a variable), the reference count is decremented. I’m not sure I understand what that means. I have a gen_server that receives a message with a binary. After processing the data, it sends it to another process. At this point, I would expect the process not to reference the binary anymore. However, calling process_info/2 shows me that the process is still somehow referencing the binary. I am new to Erlang, so I may not be using the right terminology, but I really need to understand the memory management so I don’t cause a bunch of memory leaks.

Here is the code for the gen_server that is receiving a message with a binary:

handle_info({MsgId, Message}, #state{callback = {M, F, A}} = State) ->
  apply(M, F, A ++ [processMessage(Message)]),
  {noreply, State}.

When I send one message to the gen_server, and wait several minutes, process_info(Pid, binary) still returns a reference count greater than 0 (note: Pid is the pid for the gen_server) for Message.

I would expect that this process would no longer be keeping a reference to the binary, but it appears that it is. What am I missing?

1 Like

The issue is most probably that your gen_server process never gets to garbage collect as processes only run a gc when they run out of memory.

You can read more about it here: Erlang Garbage Collector - Erlang Solutions especially the Binary Heap section.