finalisation

Andreas Raab andreas.raab at gmx.de
Fri Jan 23 00:38:09 UTC 2004


> > > > FileStream class>>fileNamed: fileName do: aBlock
> > > >      |file|
> > > >      file := self fileNamed: fileName.
> > > >      [aBlock value: file] ensure: file close
> >
> > Actually, it would be better with a ^ in front of the last line...
>
> It should also do the creation inside the ensured block. As it is, the
> process running the code could get stopped before the ensured block is
> evaluated, leaving the file dangling.

Putting the creation in the ensured block doesn't prevent that at all. It is
quite possible for #fileNamed: to be terminated before returning to the
sender and since the file variable hasn't been assigned yet this wouldn't
prevent you from leaving a dangling file any more than the above. And the
chance of the process being terminated inbetween the assignment and entering
the ensured block is - compared to the probability of being terminated
somewhere inside #fileNamed: - so remote it isn't even worth mentioning.

Really, using #ensure: in the above way is about resource management, not
dealing with horrificly complex exceptional situations[*]. For dealing with
the resource it doesn't matter at all if the file creation is inside or
outside the block - the basic deal is that once you're done with the block
we assume that you don't need the resource any longer and close it.

[*] And for all but the most horrific situations we still have finalization
to rely on. This is one of the few places where "finalization for resource
mangement" is actually helpful - since somehow the system broke the contract
to hand you the file handle, yet created it, it's the system's
responsibility to clean up afterwards.

Cheers,
  - Andreas




More information about the Squeak-dev mailing list