develooper Front page | perl.perl6.internals | Postings from February 2001

Re: Garbage collection (was Re: JWZ on s/Java/Perl/)

Thread Previous | Thread Next
Damien Neil
February 14, 2001 13:48
Re: Garbage collection (was Re: JWZ on s/Java/Perl/)
Message ID:
On Wed, Feb 14, 2001 at 05:43:31PM -0300, Branden wrote:
> 4. Why should we bother destroying an object before GC does it?
> To free system resources, like open files or database connections. Probably
> the average program won't do it never, but programs that must open several
> files sequentially (and would go out of resources if filehandles out of
> scope don't get destroyed) could probably use it to guarantee the resource
> (open file, not memory) has been freed.

I believe you are confusing object finalization with releasing
resources owned by an object.  These concepts are orthogonal.

Consider an IO::File object:

  my $fh = IO::File->new();

This creates a new object.  Space is allocated for the object, and $fh
contains a pointer to this space.  (Insert appropriate magic involving
PMCs, SVs, and the like.)


This opens a file.  $fh now holds a resource which the GC does not
track -- namely, a file descriptor.


This closes the file descriptor associated with the handle.  This
operation is, I think, what you are thinking of when you refer to
"destroying" the object.  This is not destruction, however: the object
has been instructed to release resources which it owns, but it
continues to live on.

  undef $fh;

This removes the only reference to $fh.  In the current refcounting
GC, the object which $fh referred to (not $fh, mind you -- the object
$fh pointed to) is now finalized (or "destroyed").  Other GC schemes
might defer this finalization to a later point in time.

When the object is finalized, its DESTROY method is called.  If it
holds any resources not tracked by the GC (i.e., its file descriptor),
it may release them at this time.  The GC then discards the memory
area associated with the object.  (Some GCs may, of course, do something
more clever than free()ing the memory.)

There is an important distinction here: closing the file descriptor
(or database connection, or whatever resource) does not require
finalizing the object.  Adding a method to perform this resource
deallocation requires no extensions to the memory management system --
IO::File's close method is perfectly sufficient to the task.

Adding a method to finalize the object is neither possible nor
desirable.  The only difference between finalization and releasing
resources (closing FDs, etc.) is that the memory associate with
the object itself (rather than things owned by the object) is
reclaimed by the system.  This obviously cannot be done if
references remain to the object, lest these references become
dangling pointers!

                       - Damien

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About