Re: finalize() overhead
On Nov 9, 3:30 am, Joe Seigh <jseigh...@xemaps.com> wrote:
Lew wrote:
Joe Seigh wrote:
It's not a substitute. I never said anything about using it instead
of explicit resource clean up. It would be there for the exact same
reason java.io uses it.
Well, you seem hell-bent on using finalize() despite the best advice of
several people telling you not to. You will suffer slower performance,
higher likelihood of memory issues and greater maintenance effort.
What is the "exact same reason java.io uses it"? Please explain.
More importantly, what is the actual effect of the finalize() methods in
those library classes?
Is the net value provided a boon or a detriment?
It's not best advice. Your main objections seem to be that I'm thinking of
using it on everything which will slow things down, and that I'm going
to use it for deterministic destruction. Neither is true.
As to why java.io, jdbc drivers, etc.. use it? Maybe you've never had to
support a really large code base, or you have and enjoy getting paged at
3 am about something you can't really do anything about at the moment.
Which would you rather support? An application that dies because some
combination of events caused it to execute a section of code that leaked
resources, or an application that could most likely recover those resources
before they ran out completely and issued diagnostic warnings instead.
Either you get this or you don't.
Do you trust the finalizer to release locks for you (or your caller)
if you forget to release them yourself? And do you trust your
(caller's) code to be in a sane state if a forgotten lock is suddenly
released?
Do you trust the finalizer to close sockets for you (or your caller)
if you forget to release them yourself? And do you trust your
(caller's) code to be in a sane state if a forgotten socket is
suddenly closed?
Do you trust the finalizer to close a file handle for you (or your
caller) if you forget to release them yourself? And do you trust your
(caller's) code to be in a sane state if a forgotten file handle is
suddenly closed?
These are the sorts of questions that putting cleanup in the finalizer
should be bringing up for you. In my own case, the answer to all of
them is "No.", so I don't put cleanup in the finalizer and do not rely
on finalizers to catch my own mistakes. Finalizer "cleanup" only
changes one broken state (caller did not clean up properly) into
another broken state (caller did not clean up properly and may have
been unprepared for cleanup); it at best masks bugs and never fixes
them.
You can't truly enforce correctness on code that calls your code, and
attempting to is painful for both your code and your caller's code.
The garbage collector is particularly the wrong tool to try to use to
coerce others with, since it's tuned for managing exactly one
resource: memory.