Re: Closing a database connection stored in a threadlocal upond death
of thread
Lew wrote On 06/15/07 12:35,:
Hoss Spence wrote:
On Jun 15, 10:01 am, Hoss Spence <hossspe...@hotmail.com> wrote:
Hi,
I have a situation where I open a db connection, store it in a
ThreadLocal object and need to close it on death of the Thread. Any
ideas on how to do this?
My latest thinking on this is to do it in the finalize method of the
ThreadLocal object I'm referencing. Not sure if this is sufficient.
It is not.
There is a finite probability that the finalizer will never be called.
Even it if it is, you won't know when - it could be quite a while.
Database connections tend to be precious resources. You don't want to abuse
them that way.
Always explicitly release your database connections, and ensure that that
happens. Do not leave it to chance or arbitrary scheduling. Control that it
happens, and control when it happens.
That said, finalize() is a place that can serve as a safety net to release
resources, but if they are still held by the time finalize() is called then
you have problems.
One way to ensure resource release is to have the Thread take itself down
rather than have some other Thread kill it. Then the takedown process can
handle resource management. However, if you still have a connection open as
of the Thread's senescence, you probably have suboptimal use of the resource.
It is likely that you should release the db connection much earlier.
That said, Thread cleanup when in it's in hospice can serve as a safety net to
release resources still extant, properly or otherwise.
Lew's remarks on finalize() are spot-on. As Bloch puts
it in "Effective Java," finalize() is about the garbage
collector, the garbage collector is about managing memory,
hence finalize() is about managing memory -- not resources
of other kinds.
One way to ensure the release of a DB connection (or
the closing of a file, or whatever) even in the event of
an unexpected termination is to do it in a finally block:
public void run() {
...
Thing precious = getPreciousThing();
try {
doTheWork(precious);
}
finally {
precious.hurlIntoCracksOfDoom();
}
}
The only ways this won't get executed are if your thread
gets into an infinite loop or deadlock somewhere and never
ends, or if the JVM runs so short of resources that it's
unable to run the hurlIntoCracksOfDoom() method. Either
way, you'll be in so much additional trouble that the small
matter of an un-closed DB connection will scarcely matter.
--
Eric.Sosman@sun.com