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
If you are of a sensitive disposition, look away now.
I wouldn't expect this to scale very well; it effectively doubles the number of threads in the system. There may be some use cases where it is acceptable.
public class Estragon {
  public static class Vladimir {
    Vladimir() { System.out.println("Open"); }
    public void close() { System.out.println("Close");}
  }
  private static ThreadLocal HOLDER = new ThreadLocal() {
    @Override protected Vladimir initialValue() {
      return createResource();
    }
  };
  private static Vladimir createResource() {
    final Vladimir resource = new Vladimir();
    final Thread godot = Thread.currentThread();
    new Thread() {
      @Override public void run() {
        try {
          godot.join();
        } catch (InterruptedException e) {
          // thread dying; ignore
        } finally {
          resource.close();
        }
      }
    }.start();
    return resource;
  }
  public static Vladimir getResource() {
    return HOLDER.get();
  }
}
  
Better error handling and so on is left as an exercise for the implementer.
You could also have a look at tracking the threads/resources in a ConcurrentHashMap with another thread polling isAlive. But that solution is the last resort of the desperate - objects will probably end up being checked too often or too seldom.
I can't think of anything else that doesn't involve instrumentation. AOP might work.
Connection pooling would be my favoured option.