Squeak
  links to this page:    
View this PageEdit this PageUploads to this PageHistory of this PageTop of the SwikiRecent ChangesSearch the SwikiHelp Guide
Finalization
Last updated at 3:57 pm UTC on 29 November 2003
Andreas Raab wrote to the list Nov 5, 2003:

Squeak supports "post-mortem" finalization which is a notifies _another_ object about the fact that some object just died. Squeak 3.7 (alpha)includes a bit of utility support to make this a little easier. Here (e.g.,in 3.7) you can use:
	Object>>toFinalizeSend: aSelector to: aFinalizer with: aResourceHandle
For example, you may have something like the following:
Object subclass: #MyClass
	instanceVariableNames: 'tempFiles'
	...

MyClass>>initialize
	tempFiles := OrderedCollection new.
	self toFinalizeSend: #closeTempFiles: to: self class with: tempFiles.

MyClass class>>closeTempFiles: aCollection
	"Close all the temporary files in aCollection"
	aCollection do:[:each| each close].
Some notes on the above:
a) Note the use of "self class" as the object responsible for finalization. Neither the finalizer nor the arguments must refer to the target object (this is because otherwise this object would never be garbage collected).
b) Note that if you ever assign anything (such as a new collection) to tempFiles you'll have to re-register the finalizer. Best to check with "inst var defs" from the browser to find all those places.
c) You should be aware that if you clean up the object manually, the finalization will still be run unless you deregister it manually. For example, you may add a method like
MyClass>>destroy
	"Destroy me and clean up"
	self class closeTempFiles: tempFiles.
	"Forget my finalization"
	self finalizationRegistry remove: self.