KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
When Using a thread-local database connection, closure of the connection is required when the thread exists. This I can only do if I can override the run() method of the calling thread. Even that is not a great solution, since at time of exit, I don't know if a connection has ever been opened by that thread. The problem is in fact more general: How to force a thread to call some finalisation method of a thread-local object when it exits. I looked at the sources of java 1.5 and found that the thread local map is set to null, which will eventually cause the garbage collection to call finalize() , but I don't want to count on the garbage collector. The following override seems inevitable to make sure that a database connection is closed: @Override public void remove() { get().release(); super.remove(); } where release() closes the database connection, if it has been opened. But we don't know if the thread has ever used this thread-local. If get() has never been called by this thread, then there's quite a waste of effort here: ThreadLocal.initialValue() will be called, a map will be created on this thread, etc. Further clarification and example as per Thorbjørn's comment: java.lang.ThreadLocal is a type of factory for an object that is bound to a thread. This type has a getter for the object and a factory method (typically written by the user). When the getter is called it calls the factory method only if it has never been called before by this thread. Using ThreadLocal allows a developer to bind a resource to a thread even if the thread code was written by a third party. Example: Say we have a resource Type called MyType and we want to have one and only one of it per thread. Define in the using class: private static ThreadLocal<MyType> resourceFactory = new ThreadLocal<MyType>(){ @ove
Tags (comma-separated)
Save Edits
Cancel