How to force a Java thread to close a thread-local database connection

后端 未结 9 1121
鱼传尺愫
鱼传尺愫 2021-02-13 12:41

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

9条回答
  •  爱一瞬间的悲伤
    2021-02-13 13:10

    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.

提交回复
热议问题