Common Lisp/Beyond ANSI Common Lisp/User Control of GC
The Common Lisp specification says very little about garbage collection, GC. GC is traditionally treated as a black box that the user never has to worry about: if an object is accessible, then it is still allocated, so no memory errors can occur. There are times, however, that it is useful to gain a little control over garbage collection and memory management. Almost every common lisp implementation has a function called
GC that starts the garbage collection process.
GC is fairly standard, but other features such as weak pointers, weak hashes, and object finalization have much less standard interfaces, if they are present at all. We will be using the compatibility layer trivial-garbage to provide a standard interface.
When the GC reclaims an object, the space is usually just freed. In some circumstances, however, it can be useful to have a procedure that runs when the garbage collector reclaims the data. Object finalization (not to be confused with class finalization) allows you to set such a procedure.
An example of when you might want to use this is when you are allocating foreign memory (memory that is not under control of the garbage collector). Finalization allows you to put that memory under the control of the garbage collector.
(defun get-foreign-array (size) ... (tg:finalize ...))
We have wrapped our foreign pointer in a Lisp object and set up a finalization procedure for that object. The finalization procedure frees the memory, removing memory leaks.