Re: finalize() overhead
Joe Seigh wrote:
I guess overriding finalize() isn't recommended too much because
of it's adverse effect on GC performance.
One of a few reasons.
But I assume that if it's used a lot.
What did you mean by this?
You need finalize() for things like guaranteeing proper clean up of non-memory resources like file descriptors and
db connections. One way anyway.
No, you don't. In fact, you pretty much need to avoid finalize() for these
purposes.
So this sort of use of finalize is considered acceptable? Or should
No.
it be avoided at all costs even if you leak file descriptors or
whatnot?
Finalizers should not be "avoided at all costs". Nor should you use them to
release "file descriptors or whatnot". Or for pretty much anything else,
except for when it makes sense. Which is nearly never.
Remember that many finalizable objects will *never* have their finalize()
method called. If you are relying on finalize() to free resources you're
going to run out of resources. Even if such an object does get its finalize()
called, it still takes a couple of GC cycles to get rid of it altogether,
which does potentially strain your memory resources.
Garbage collection is for *memory* management, not resource management.
A better way to release resources would be to use a Reference queue to tell
when an object is finished, and run a thread to pull objects off the queue and
dispose (possibly with a method called dispose()) of their resources.
A typical way to release resources is through the use of try ... finally
blocks. Once a resource is allocated, enclose its further use in a try()
block whose finally() block releases the resource.
You should avoid overriding finalize() except, a) to release JNI memory when
an object is garbage collected, or b) for when it really, really makes sense.
Which is nearly never.
--
Lew