Re: Closing a database connection stored in a threadlocal upond death
of thread
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