How to Detect JDBC Connection Leakages with C3P0

First of all I must say that, the whole credit for discovering this feature goes to my collegue İlker Çelik. In a big codebase with lots of 3rd party libraries and frameworks interacting with JDBC connections it might be difficult to trap JDBC connection leakages, that is open connections left in application.

C3P0 connection pool has a nice option to kill unreturned connections left in application. unreturnedConnectionTimeout attribute is for this purpose. If you give it a positive integer value, it waits for given seconds and then destroys those connections whose close method are not called yet. In order to see who is responsible for the leakage you must use it with debugUnreturnedConnectionStackTraces attribute in combination.

If you give positive value to unreturnedConnectionTimeout, C3P0 will capture stacktrace via an exception in which your application opens connection, and setting debugUnreturnedConnectionStackTraces to true will show this stacktrace. You can find detailed information about this feature of C3P0 here.