Debian Codegraph @

external/bdwgc/doc/finalization.md

raw
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 (e.g. Irix)
41 allow hundreds or thousands of open files, and this is typically not
42 an issue.
43 * Finalization code may be run anyplace an allocation or other call to the
44 collector takes place. In multi-threaded programs, finalizers have to obey
45 the normal locking conventions to ensure safety. Code run directly from
46 finalizers should not acquire locks that may be held during allocation.
47 This restriction can be easily circumvented by registering a finalizer which
48 enqueues the real action for execution in a separate thread.
49
50 In single-threaded code, it is also often easiest to have finalizers queue
51 actions, which are then explicitly run during an explicit call by the user's
52 program.
53
54 # Topologically Ordered Finalization
55
56 Our _conservative garbage collector_ supports a form of finalization (with
57 `GC_register_finalizer`) in which objects are finalized in topological order.
58 If _A_ points to _B_ and both are registered for finalization, it is
59 guaranteed the _A_ will be finalized first. This usually guarantees that
60 finalization procedures see only unfinalized objects.
61
62 This decision is often questioned, particularly since it has an obvious
63 disadvantage. The current implementation finalizes long chains of finalizable
64 objects one per collection. This is hard to avoid, since the first finalizer
65 invoked may store a pointer to the rest of the chain in a global variable,
66 making it accessible again. Or it may mutate the rest of the chain.
67
68 Cycles involving one or more finalizable objects are never finalized.
69
70 # Why topological ordering?
71
72 It is important to keep in mind that the choice of finalization ordering
73 matters only in relatively rare cases. In spite of the fact that it has
74 received a lot of discussion, it is not one of the more important decisions
75 in designing a system. Many, especially smaller, applications will never
76 notice the difference. Nonetheless, we believe that topologically ordered
77 finalization is the right choice.
78
79 To understand the justification, observe that if _A_'s finalization procedure
80 does not refer to _B_, we could fairly easily have avoided the dependency.
81 We could have split _A_ into _A'_ and _A''_ such that any references to _A_
82 become references to _A'_, _A'_ points to _A''_ but not vice-versa, only
83 fields needed for finalization are stored in _A''_, and _A''_ is enabled for
84 finalization. (`GC_register_disappearing_link` provides an alternative
85 mechanism that does not require breaking up objects.)
86
87 Thus assume that _A_ actually does need access to _B_ during finalization.
88 To make things concrete, assume that _B_ is finalizable because it holds
89 a pointer to a C object, which must be explicitly deallocated. (This is likely
90 to be one of the most common uses of finalization.) If _B_ happens to be
91 finalized first, _A_ will see a dangling pointer during its finalization. But
92 a principal goal of garbage collection was to avoid dangling pointers.
93
94 Note that the client program could enforce topological ordering even if the
95 system did not. A pointer to _B_ could be stored in some globally visible
96 place, where it is cleared only by _A_'s finalizer. But this puts the burden
97 to ensure safety back on the programmer.
98
99 With topologically ordered finalization, the programmer can fail to split
100 an object, thus leaving an accidental cycle. This results in a leak, which
101 is arguably less dangerous than a dangling pointer. More importantly, it is
102 _much_ easier to diagnose, since the garbage collector would have to go out of
103 its way not to notice finalization cycles. It can trivially report them.
104
105 Furthermore unordered finalization does not really solve the problem
106 of cycles. Consider the above case in which _A_'s finalization procedure
107 depends on _B_, and thus a pointer to _B_ is stored in a global data
108 structure, to be cleared by _A_'s finalizer. If there is an accidental pointer
109 from _B_ back to _A_, and thus a cycle, neither _B_ nor _A_ will become
110 unreachable. The leak is there, just as in the topologically ordered case, but
111 it is hidden from easy diagnosis.
112
113 A number of alternative finalization orderings have been proposed, e.g. based
114 on statically assigned priorities. In our opinion, these are much more likely
115 to require complex programming discipline to use in a large modular system.
116 (Some of them, e.g. Guardians proposed by Dybvig, Bruggeman, and Eby, do avoid
117 some problems which arise in combination with certain other collection
118 algorithms.)
119
120 Fundamentally, a garbage collector assumes that objects reachable via pointer
121 chains may be accessed, and thus should be preserved. Topologically ordered
122 finalization simply extends this to object finalization; an finalizable object
123 reachable from another finalizer via a pointer chain is presumed to be
124 accessible by the finalizer, and thus should not be finalized.
125
126 # Programming with topological finalization
127
128 Experience with Cedar has shown that cycles or long chains of finalizable
129 objects are typically not a problem. Finalizable objects are typically rare.
130 There are several ways to reduce spurious dependencies between finalizable
131 objects. Splitting objects as discussed above is one technique. The collector
132 also provides `GC_register_disappearing_link`, which explicitly nils a pointer
133 before determining finalization ordering.
134
135 Some so-called "operating systems" fail to clean up some resources associated
136 with a process. These resources must be deallocated at all cost before process
137 exit whether or not they are still referenced. Probably the best way to deal
138 with those is by not relying exclusively on finalization. They should
139 be registered in a table of weak pointers (implemented as disguised pointers
140 cleared by the finalization procedure that deallocates the resource). If any
141 references are still left at process exit, they can be explicitly deallocated
142 then.
143
144 # Getting around topological finalization ordering
145
146 There are certain situations in which cycles between finalizable objects are
147 genuinely unavoidable. Most notably, C++ compilers introduce self-cycles
148 to represent inheritance. `GC_register_finalizer_ignore_self` tells the
149 finalization part of the collector to ignore self cycles. This is used by the
150 C++ interface.
151
152 Finalize.c actually contains an intentionally undocumented mechanism for
153 registering a finalizable object with user-defined dependencies. The problem
154 is that this dependency information is also used for memory reclamation, not
155 just finalization ordering. Thus misuse can result in dangling pointers even
156 if finalization does not create any. The risk of dangling pointers can be
157 eliminated by building the collector with `-DJAVA_FINALIZATION`. This forces
158 objects reachable from finalizers to be marked, even though this dependency
159 is not considered for finalization ordering.