Sunday, August 20, 2006

Catching garbage collecting

I see many times Squeakers ask questions about finalizing objects when the garbage collector is called.

Squeak startups a finalizing process inside WeakArray which finalize values of its Weak dependents (for example WeakRegistry objects).

First of all you need to subclass Object, call the new class GCTest.
Add a #finalize method to it:
    Transcript show: 'finalizing'

Now open a Transcript and a Workspace and doIt this:
gcTest _ GCTest new.
WeakRegistry default add: gcTest

Now close the Workspace and look at the Transcript saying 'finalizing'.

Usually, you won't register your objects into the default WeakRegistry, you can also create your own WeakRegistry.
Take care the WeakRegistry is also garbage collected, so you need to place it as a global variable of your base class for instance: look at Socket or StandardFileStream as valid examples.

NB: when creating a new WeakRegistry, it's automatically added as a Weak dependent in WeakArray

No comments: