>>finalize questions

Bert Freudenberg bert at impara.de
Sun Aug 20 09:53:47 UTC 2006


Am 20.08.2006 um 07:48 schrieb Michael van der Gulik:
> 1. What does Object>>finalize do?
>
> It appears not to do much at all.

Right. It's simply the default implementation when a WeakRegistry  
sends #finalize to one of its registered objects, to prevent a  
MessageNotUnderstood walkback.

> Also, "w := WeakArray with: (Dunce new)" doesn't call finalize  
> either...

WeakArrays are not to support finalization but to hold weakly onto  
its elements (replaced by nil when GCed).

For finalization use a WeakRegistry:

	WeakRegistry default add: Dunce new.
	Smalltalk garbageCollect.

> 2. I have an object with a process "in" it. How can I make sure  
> that process is terminated when there are no more references to  
> that object?

Terminate the process when you release the last reference to the  
object. Like, send #release to your object before setting the ref to  
nil.

Only as a last resort, use finalization.

An object cannot finalize itself, because that would create a strong  
reference! Instead, #finalize is sent to an object's #executor. By  
default, the executor is a clone of the object (held strongly) and  
#finalize is sent to that clone.

Ponder that.

It means that any change to instance variables after registering for  
finalization does not affect the executor. So you must first create  
the process, then register for finalization. When the process inst  
variable changes, you need to register a finalizer again.

You can verify this by using "Dunce allInstances". For debugging  
purposes, it's helpful to modify #printOn: to indicate whether this  
instance is an executor or not. I usually set some inst var to nil in  
#actAsExecutor, because the executor only needs access to the inst  
vars it must finalize.

Using this technique, you can verify that the executor survives the  
GC that swiped the original object. Only the next GC will collect the  
executor, too.

In short - use finalization only if you really, really need it and  
understand the implications ;-)

- Bert -




More information about the Squeak-dev mailing list