Finalization

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Finalization

Sean P. DeNigris
Administrator
What are the (best?) sources of finalization documentation? I saw posts on the list about wanting some and possibly creating some, but none providing links to actual docs.

I want to share an experience report in case it helps anyone else…

I was implementing a temp file object which should auto delete from the filesystem when it is garbage collected.

I did:
```smalltalk
Tempfile>>#initializeWithOrigin: aSymbol path: aPath
   WeakRegistry default add: self.
   ^ super initializeWithOrigin: aSymbol path: aPath
```
and then:
```smalltalk
Tempfile>>#finalize
   self delete
```

The instVars were nil, so I couldn't delete the file, and I mistakenly assumed that they were nil-ed out during finalization. Eventually, I realized that it was a bug in my code due to a lack of understanding about the initialization mechanism. When an object is added to a weak registry, apparently a shallow copy is what is actually added. In my initialization method, I added the object before it was initialized, so the copy didn’t contain the information it needed to finalize the object. Simply reversing the two statements made it work.

Lesson learned: objects must treat any state needed during finalization as immutable; at least once the object is added to the weak registry.

The main (non-blocking) question remaining is which registry to use. I see other classes that implement `finalize` use their own custom registry - why?


Cheers,
Sean