Given a JVM connecting to a PostgreSQL database (on Linux), is there a way to find out which thread in Java is responsible for a process in the database?
NB: I'm debugging a resource-leak bug, which shows up as some idle-in-transaction processes in the database. It would be useful to match these up with the thread responsible, as the thread name will narrow down the search.
You could set application_name (with the SET
statement) to something that you can match up with the Java thread name.
A useful trick is to send a SIGQUIT signal to the Java process, e.g.
kill -QUIT your_process_id
Which will not kill it, but will tell it to print a thread dump. This will list all the threads, with a backtrace of what they are currently doing. Unfortunately this won't usually contain something as obvious as "conn.setAutoCommit(false)", but it will tell you where each thread is.
You can then find those points in the code and attempt to trace back to see if any are preceeded by transaction begins that are unmatched by commits/rollbacks.
Another thing that is useful when the application is being written is to have a common place where connections are created and controlled (i.e. yet another abstraction layer!). This becomes a good place to put statements for logging when connections are created and assigned to threads, and when a transaction is begun on one of them.
config.setCloseConnectionWatch()
-- which creates a helper thread to watch for un-released connections (comes with a performance warning) - Daniel Winterstein 2012-04-06 09:01