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

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

    The normal JDBC practice is that you close the Connection (and Statement and ResultSet) in the very same method block as you'd acquired it.

    In code:

    Connection connection = null;
    
    try {
        connection = getConnectionSomehow();
        // Do stuff.
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                ignoreOrLogItButDontThrowIt(e);
            }
        }
    }
    

    Keeping this in mind, your question makes me think that there's something wrong in your design. Acquiring and closing those kind of expensive and external resources in the shortest scope will save the application from potential resource leaks and crashes.

    If your original intent was to improve connecting performance, then you need to take a look for connection pooling. You can use for example the C3P0 API for this. Or if it's a webapplication, use the appserver's builtin connection pooling facilities in flavor of a DataSource. Consult the appserver specific documentation for details.

提交回复
热议问题