From: Rick DeNatale Date: 2009-04-30T02:13:03+09:00 Subject: Re: Opposite of initialize On Tue, Apr 28, 2009 at 7:42 PM, 7stud -- wrote: > Hassan Schroeder wrote: >> On Tue, Apr 28, 2009 at 10:10 AM, Robert Klemme >> wrote: >> >>>>> I'm looking for the opposite function of initialize() as I need to >>>>> call something before an object is "destroyed". >> >>> And the finalizer is called *after* the object has gone! >> >> So "before" it's destroyed and "after" it's destroyed are two different >> things. >> > > Not only that: > > 1) "it goes out of scope and there are no more references to the object > so the object is ready to be garbage collected" > > and > > 2) "the object is actually garbage collected and destroyed" > > are two different things.  The actual destruction may happen only after > your program ends. In every GCd language I've used, including Smalltalk, Java and Ruby, finalization has always turned out to be an unreliable mechanism for doing resource cleanup. The role of the GC is actually to make sure that objects don't get freed prematurely, a GC's primary job is to prevent 'dangling' pointer problems. Reclaiming memory is a secondary goal. So there's no guarantee that an object will be freed as soon as it's no longer reference-able. And as you point out, objects might only be reclaimed by the OS after the program exits. Over the past 25 years or so, I've come to regard finalization as an "attractive nuisance." -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale