Garbage Collection

The memory used by objects and ground expressions that cannot be accessed any more is considered as garbage, and is reclaimed automatically.

The point is that, at run time, Refal Plus programs can create objects, but there is no explicit way in which they can be destroyed. Thus, the computer memory may well be filled with new and new objects, although many of them may not be needed any more. Theoretically, this is no problem, but, in practice, Refal programs are to be run by real computers with limited memory capacity. For that reason, all Refal Plus implementations include a garbage collector.

Garbage collection is automatically started each time the free memory is exhausted, in order to find and destroy all objects that, being inaccessible via the references contained in variable values, are thus unable to influence the program's behavior.

The following figure schematically shows the variable values as well as several objects along with their contents. The stars denote the parts of expressions that are not reference symbols. To facilitate the discussion, all objects are labeled with numbers. The corresponding numbers denote reference symbols appearing in the ground expressions.

Figure 1. Objects and references.
    VARIABLE VALUES:
    [* * 1 * * * * * * 2 * * * * *]
    
    1:[* * * 4]
    2:[4 * * 5]
    3:[* * 5]
    4:[* * *]
    5:[* 6 * 3]
    6:[* * 4 *]
    7:[3 * 8]
    8:[* 7]

It can be easily seen that reference 1 appearing in the variable values enables the access to object 1 and, indirectly (via object 1), to object 4, whereas reference 2 enables the access to object 2 and, indirectly (via object 2), to objects 4, 5, 6, 3. Thus, there is no way of getting information from objects 7 and 8. Therefore, if the garbage collection started at this moment, objects 7 and 8 would be destroyed. Now, if reference 1 were removed from the variable values, object 1 would become inaccessible. But, if reference 1 were retained, and reference 2 removed, then all the objects would become inaccessible, except objects 1 and 4.