[gclist] RE: Destructor functions and GC
Thomas Weitzel
100335.127@compuserve.com
07 Mar 96 10:49:39 EST
Dave wrote:
> Some of the revent posts on GC and OO have reminded me of a problem that
> occurred to me some years ago: how does a GC interact with destructor
> functions?
I definitely agree that it is desirable to have the opportunity to have a
finalization function
called when an object is "freed" by the garbage collector. The typical situation
when one
wants to have this is when an object is associated with some "external" resource
like a disk file (or a semaphore).
I've seen some advice that it is considered bad practice to rely on
finalization, but I don't know how to deal with it in some other way without
introducing the possibility of invalid references (like the attempt to read from
a file which was just closed by some innocent looking piece of code). Any
opinions on this?
I think how that can be achieved depends on the sort of GC algorithm you use.
Reference counting or Mark-And-Sweep make it easy to call a finalization
function, because objects are actually visited and freed explicitly.
Copying and pseudo-copying (i.e. Baker's treadmill) algorithms do not explicitly
free objects.
They just separate the living objects from the dead ones and "declare" the old
area to be
free. But there is still a way to have finalization functions called in this
situation: Put the objects into a "weak array" associated with the finalization.
A weak array is a container that doesn't prevent it's members to become garbage.
When an area free occurs, the algorithm can scan the weak arrays and spot the
garbage objects.
I've seen this solution in the ParcPlace Smalltalk 80 implementation. Some
caution needs to be taken when implementing this model because any dereferencing
of the old object is invalid, so you need to put the information you need for
finalization in a separate place!
Tom