Question

What is the standard approach in Java to test whether a MySQL connection has been timed out by the server / keep the conneciton alive? (com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 73.596.145 milliseconds ago ...)

Some articles recommended periodic pinging to keep the connection alive. I could start a separated thread which does this, ok. However, is there some easy test that I could perform and reconnect only if necessary? Or is periodic pinging the best-performance way to go here?

boolean java.sql.Connection.isClosed() states "This method is guaranteed to return true only when it is called after the method Connection.close has been called" and I guess that this will not do the job for me.

I could internally keep track of seconds since last request, compare that to select @@wait_timeout; and reconnect if too much time has passed.

So, what is the standard approach to know if the connection has timed out / keep the connection alive?

Thanks a lot in advance!

Was it helpful?

Solution

I have encountered the same problem.

A solution that must be tested is to call the "isValid(int timeout)" method from the java.sql.Connection

Or set autoreconnect in mysql: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html

Or change the timeout in mysql (default = 8 hours): http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_wait_timeout

EDIT: but I think that the best pratice is to open the connection during a transaction and then close it directly after that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top