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

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

    I think in the general case there is no good solution for this, other than the classic: Code that gets the resource has to be responsible for closing it.

    In the specific case, if you are calling threads to this degree you could pass in the connection to your methods at the start of the thread, either with a method that takes a custom parameter or via some form of Dependency Injection. Then since you have the code that supplies the connection, you have the code that removes it.

    A Dependency Injection based on annotations might work here, as code that doesn't require the connection won't get one and therefore wouldn't need to be closed, but it sounds like your design is too far along to retrofit something like that.

提交回复
热议问题