How does the garbage collector really works?

Ulf Wiger <>
Wed May 17 10:15:14 CEST 2000


On Tue, 16 May 2000, Jonas Jerfsten wrote:

>Hi!
>I have a question about how the garbage collector (gc) in Erlang
>works. I am working on a module that performs a file:consult/1 on a
>large file and then stores the data in an ets-table. All that is
>done in the init of the process. I have performed memory analysis on
>the process using erlang:trace/3 and process_info/2. It seems as if
>the file:consult/1 function call results in a large memory
>allocation and that the process will hold on to that memory even
>after the calling function has gone out of scope. If I do not make
>any further function calls to the process, it seems as if the gc
>will not go in and free the memory. That means that when the process
>is initialised, it will allocate a lot of memory and keep it until
>the process is scheduled again. Correct? Or am I making incorrect
>assumptions from my memory analysis? If the process is not scheduled
>again, when will the gc free the memory?
>
>/Jonas Jerfsten

Hi,

You are correct, and the answer is: never -- unless...

The garbage collector will allocate an increasingly larger heap, if
the process keeps growing (i.e. the GC sweep is unable to free enough
memory to allocate the new data*. It can happen that the function
finishes before filling up the new heap. You will then be stuck with
the large heap (with mostly garbage), possibly forever, if the process
doesn't get to perform more work. As soon as the process starts
executing a new job, it will most likely create more garbage, and a
garbage collection sweep will be triggered.

You can force a garbage collection by calling
erlang:garbage_collect(). This can be useful in cases where you *know*
that the process will not execute again for a long time (perhaps
never).

In older versions of OTP (I think before R5B), you had to specifically
call a function after calling garbage_collect(), for the GC to
actually take place, but I'm pretty sure this has been fixed.

/Uffe

* Using a fibonacci sequence if I'm not mistaken.
-- 
Ulf Wiger, Chief Designer AXD 301         <>
Ericsson Telecom AB                          tfn: +46  8 719 81 95
Varuvägen 9, Älvsjö                          mob: +46 70 519 81 95
S-126 25 Stockholm, Sweden                   fax: +46  8 719 43 44




More information about the erlang-questions mailing list