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

后端 未结 9 1122
鱼传尺愫
鱼传尺愫 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:12

    I don't really understand why you are not using traditional connection pooling. But I shall assume you have your reasons.

    How much freedom do you have? As some DI frameworks do support object life cycles and thread-scoped variables (all nicely proxied). Could you use one of them? I think Spring would do this all out of the box, while Guice would need a 3rd party lib to handle life cycles and thread scopes.

    Next how much control do you have on either the creating of the ThreadLocal variable or the creation of threads? I am guessing you have complete control on the ThreadLocal but limited to none on the creation of threads?

    Could you use Aspect-oriented programming to monitor for new Runnable or Threads extending the run() method to include the clean up? You will also need to extend the ThreadLocal so it can register itself.

提交回复
热议问题