title: In Java, how to close ThreadLocal resource when thread is finished
body: <p>I have a third party Java library that provides a resource.</p>
  
  <pre><code>TheResource resource = TheResource.create()
  </code></pre>
  
  <p>Sometime later, when I'm done with the resource, I'm supposed to close the resource</p>
  
  <pre><code>resource.close()
  </code></pre>
  
  <p>According to the library documentation, the resource I create is a ThreadLocal variable. That means the resource is created per thread, and it sticks to the thread. My question is, is it possible to call the <code>close()</code> method automatically when the associated thread is finished? I think I can do it if the thread is my own custom thread because I can engage with the lifecycle of the thread. But my question is about those threads provided by the system.</p>
  
  <p>For instance, in Android's <a href="http://developer.android.com/training/sync-adapters/creating-sync-adapter.html" rel="nofollow">SyncAdapter</a> provides a thread for you. And I don't know how the thread is finished. I'm wondering if there's some kind of 'hook' mechanism in terms of threads' lifecycle so that I can close ThreadLocal resources of the threads.</p>