| 1 |
# Finalization |
| 2 |
|
| 3 |
Many garbage collectors provide a facility for executing user code just before |
| 4 |
an object is collected. This can be used to reclaim any system resources |
| 5 |
or non-garbage-collected memory associated with the object. Experience has |
| 6 |
shown that this can be a useful facility. It is indispensable in cases |
| 7 |
in which system resources are embedded in complex data structures (e.g. file |
| 8 |
descriptors in the `include/cord.h`). |
| 9 |
|
| 10 |
Our collector provides the necessary functionality through |
| 11 |
`GC_register_finalizer` in `include/gc.h`, or by inheriting from `gc_cleanup` |
| 12 |
in `include/gc_cpp.h`). |
| 13 |
|
| 14 |
However, finalization should not be used in the same way as C++ destructors. |
| 15 |
In well-written programs there will typically be very few uses |
| 16 |
of finalization. (Garbage collected programs that interact with explicitly |
| 17 |
memory-managed libraries may be an exception.) |
| 18 |
|
| 19 |
In general the following guidelines should be followed: |
| 20 |
|
| 21 |
* Actions that must be executed promptly do not belong in finalizers. They |
| 22 |
should be handled by explicit calls in the code (or C++ destructors if you |
| 23 |
prefer). If you expect the action to occur at a specific point, this |
| 24 |
is probably not hard. |
| 25 |
* Finalizers are intended for resource reclamation. |
| 26 |
* Scarce system resources should be managed explicitly whenever convenient. |
| 27 |
Use finalizers only as a backup mechanism for the cases that would be hard |
| 28 |
to handle explicitly. |
| 29 |
* If scarce resources are managed with finalization, the allocation routine |
| 30 |
for that resource (e.g. open for file handles) should force a garbage |
| 31 |
collection (two if that does not suffice) if it finds itself short of the |
| 32 |
resource. |
| 33 |
* If extremely scarce resources are managed by finalization (e.g. file |
| 34 |
descriptors on systems which have a limit of 20 open files), it may |
| 35 |
be necessary to introduce a descriptor caching scheme to hide the resource |
| 36 |
limit. (E.g., the program would keep real file descriptors for the 20 most |
| 37 |
recently used logically open files. Any other needed files would be closed |
| 38 |
after saving their state. They would then be reopened on demand. |
| 39 |
Finalization would logically close the file, closing the real descriptor |
| 40 |
only if it happened to be cached.) Note that most modern systems allow |
| 41 |
thousands of open files, and this is typically not an issue. |
| 42 |
* Finalization code may be run anyplace an allocation or other call to the |
| 43 |
collector takes place. In multi-threaded programs, finalizers have to obey |
| 44 |
the normal locking conventions to ensure safety. Code run directly from |
| 45 |
finalizers should not acquire locks that may be held during allocation. |
| 46 |
This restriction can be easily circumvented by calling |
| 47 |
`GC_set_finalize_on_demand(1)` at program start and creating a separate |
| 48 |
thread dedicated to periodic invocation of `GC_invoke_finalizers()`. |
| 49 |
|
| 50 |
In single-threaded code, it is also often easiest to have finalizers queued |
| 51 |
and, then to have them explicitly executed by `GC_invoke_finalizers()`. |
| 52 |
|
| 53 |
## Topologically ordered finalization |
| 54 |
|
| 55 |
Our _conservative garbage collector_ supports a form of finalization (with |
| 56 |
`GC_register_finalizer`) in which objects are finalized in topological order. |
| 57 |
If _A_ points to _B_ and both are registered for finalization, it is |
| 58 |
guaranteed the _A_ will be finalized first. This usually guarantees that |
| 59 |
finalization procedures see only unfinalized objects. |
| 60 |
|
| 61 |
This decision is often questioned, particularly since it has an obvious |
| 62 |
disadvantage. The current implementation finalizes long chains of finalizable |
| 63 |
objects one per collection. This is hard to avoid, since the first finalizer |
| 64 |
invoked may store a pointer to the rest of the chain in a global variable, |
| 65 |
making it accessible again. Or it may mutate the rest of the chain. |
| 66 |
|
| 67 |
Cycles involving one or more finalizable objects are never finalized. |
| 68 |
|
| 69 |
## Why topological ordering? |
| 70 |
|
| 71 |
It is important to keep in mind that the choice of finalization ordering |
| 72 |
matters only in relatively rare cases. In spite of the fact that it has |
| 73 |
received a lot of discussion, it is not one of the more important decisions |
| 74 |
in designing a system. Many, especially smaller, applications will never |
| 75 |
notice the difference. Nonetheless, we believe that topologically ordered |
| 76 |
finalization is the right choice. |
| 77 |
|
| 78 |
To understand the justification, observe that if _A_'s finalization procedure |
| 79 |
does not refer to _B_, we could fairly easily have avoided the dependency. |
| 80 |
We could have split _A_ into _A'_ and _A''_ such that any references to _A_ |
| 81 |
become references to _A'_, _A'_ points to _A''_ but not vice-versa, only |
| 82 |
fields needed for finalization are stored in _A''_, and _A''_ is enabled for |
| 83 |
finalization. (`GC_register_disappearing_link` provides an alternative |
| 84 |
mechanism that does not require breaking up objects.) |
| 85 |
|
| 86 |
Thus assume that _A_ actually does need access to _B_ during finalization. |
| 87 |
To make things concrete, assume that _B_ is finalizable because it holds |
| 88 |
a pointer to a C object, which must be explicitly deallocated. (This is likely |
| 89 |
to be one of the most common uses of finalization.) If _B_ happens to be |
| 90 |
finalized first, _A_ will see a dangling pointer during its finalization. But |
| 91 |
a principal goal of garbage collection was to avoid dangling pointers. |
| 92 |
|
| 93 |
Note that the client program could enforce topological ordering even if the |
| 94 |
system did not. A pointer to _B_ could be stored in some globally visible |
| 95 |
place, where it is cleared only by _A_'s finalizer. But this puts the burden |
| 96 |
to ensure safety back on the programmer. |
| 97 |
|
| 98 |
With topologically ordered finalization, the programmer can fail to split |
| 99 |
an object, thus leaving an accidental cycle. This results in a leak, which |
| 100 |
is arguably less dangerous than a dangling pointer. More importantly, it is |
| 101 |
_much_ easier to diagnose, since the garbage collector would have to go out of |
| 102 |
its way not to notice finalization cycles. It can trivially report them. |
| 103 |
|
| 104 |
Furthermore unordered finalization does not really solve the problem |
| 105 |
of cycles. Consider the above case in which _A_'s finalization procedure |
| 106 |
depends on _B_, and thus a pointer to _B_ is stored in a global data |
| 107 |
structure, to be cleared by _A_'s finalizer. If there is an accidental pointer |
| 108 |
from _B_ back to _A_, and thus a cycle, neither _B_ nor _A_ will become |
| 109 |
unreachable. The leak is there, just as in the topologically ordered case, but |
| 110 |
it is hidden from easy diagnosis. |
| 111 |
|
| 112 |
A number of alternative finalization orderings have been proposed, e.g. based |
| 113 |
on statically assigned priorities. In our opinion, these are much more likely |
| 114 |
to require complex programming discipline to use in a large modular system. |
| 115 |
(Some of them, e.g. Guardians proposed by Dybvig, Bruggeman, and Eby, do avoid |
| 116 |
some problems which arise in combination with certain other collection |
| 117 |
algorithms.) |
| 118 |
|
| 119 |
Fundamentally, a garbage collector assumes that objects reachable via pointer |
| 120 |
chains may be accessed, and thus should be preserved. Topologically ordered |
| 121 |
finalization simply extends this to object finalization; an finalizable object |
| 122 |
reachable from another finalizer via a pointer chain is presumed to be |
| 123 |
accessible by the finalizer, and thus should not be finalized. |
| 124 |
|
| 125 |
## Programming with topological finalization |
| 126 |
|
| 127 |
Experience with Cedar has shown that cycles or long chains of finalizable |
| 128 |
objects are typically not a problem. Finalizable objects are typically rare. |
| 129 |
There are several ways to reduce spurious dependencies between finalizable |
| 130 |
objects. Splitting objects as discussed above is one technique. The collector |
| 131 |
also provides `GC_register_disappearing_link`, which explicitly nils a pointer |
| 132 |
before determining finalization ordering. |
| 133 |
|
| 134 |
Some so-called "operating systems" fail to clean up some resources associated |
| 135 |
with a process. These resources must be deallocated at all cost before process |
| 136 |
exit whether or not they are still referenced. Probably the best way to deal |
| 137 |
with those is by not relying exclusively on finalization. They should |
| 138 |
be registered in a table of weak pointers (implemented as disguised pointers |
| 139 |
cleared by the finalization procedure that deallocates the resource). If any |
| 140 |
references are still left at process exit, they can be explicitly deallocated |
| 141 |
then. |
| 142 |
|
| 143 |
## Getting around topological finalization ordering |
| 144 |
|
| 145 |
There are certain situations in which cycles between finalizable objects are |
| 146 |
genuinely unavoidable. Most notably, C++ compilers introduce self-cycles |
| 147 |
to represent inheritance. `GC_register_finalizer_ignore_self` tells the |
| 148 |
finalization part of the collector to ignore self cycles. This is used by the |
| 149 |
C++ interface. |
| 150 |
|
| 151 |
Finalize.c actually contains an intentionally undocumented mechanism for |
| 152 |
registering a finalizable object with user-defined dependencies. The problem |
| 153 |
is that this dependency information is also used for memory reclamation, not |
| 154 |
just finalization ordering. Thus misuse can result in dangling pointers even |
| 155 |
if finalization does not create any. The risk of dangling pointers can be |
| 156 |
eliminated by building the collector with `-DJAVA_FINALIZATION`. This forces |
| 157 |
objects reachable from finalizers to be marked, even though this dependency |
| 158 |
is not considered for finalization ordering. |