Java – how do I track orphaned JDBC connections that are not closed?

We found an error in the old code that did not close the connection This is a simple solution, but I want to know how we can prove that it is fixed You can choose whether to use connection pool For pooled use, it is easy to add monitoring to the pool, but how do we track those unclosed isolated connections when the connection pool is not used? Is it like any other memory leak?

The error appears to be basically a cut and paste error We have some classes for managing database connections, so it looks like the following:

OurDBConn conn1 = ConnectionManager.getConnection();
try {
  // business logic
} catch () {
  //
} finally {
  ConnectionManager.returnConnection(conn1);
}

/// and then later in the same method
OurDBConn conn2 = ConnectionManager.getConnection();
try {
  // business logic
} catch () {
  //
} finally {
  ConnectionManager.returnConnection(conn1); // NOTE Error: conn1 should be conn2
}

I don't know why early coders didn't just reuse the original connection, but that's its essence

(start edit / append)

Yes, the connection code is also ours, so I can use the answer given

However, I don't think I asked the right question, although the following answers answered my questions I'm not sure what the right stack overflow should do; Ask another question or edit one?

One question I should ask is: how do these isolated and unclosed connections show up in system performance? In addition, since these connection objects only exist within the scope of a method, are connections eligible for garbage collection? Then, if they are gc'ed, what is the impact of open connections being gc'ed?

(end edit)

Solution

Assuming that the connection manager is also your own code, you can store the initialized connections (and stack traces) in the mapping in the connection manager and delete them when they are returned Therefore, at any time, the mapped keyset is an unreturned connection set. You can look up the value in the mapping to find the code that created them and never released them (if the connection is not a suitable map key, you can use some unique ID or connection number or other - the actual value does not matter)

Then just add some appropriate ways to access the map on demand, and you'll be fine Depending on your environment, adding a close hook to dump map content to a file and / or adding a jconsole interface to find unclosed connection sets in running code are good choices

If the connection manager is not your code, you can still use aspects to achieve the same functionality

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>