Tobi
Tobi

Reputation: 932

Keep database connection open or reopen it everytime it is needed?

I know this sort of question has been asked for a few times, I read some of them but did not get any smarter. My Java application is connecting to a database server via JDBC through a SSH Tunnel. The tunnel is opened once at beginning. When starting I opened the database connection everytime it is used. Due to changes in the app I needed the connection opened on startup and decided to keep it open until my application is closed. When I close the app I sometimes, not always, get following error:

 - Could not retrieve transation read-only status server

 java.sql.SQLException: Could not retrieve transation read-only status server
 Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

 The last packet successfully received from the server was 369.901 milliseconds ago.  The last packet sent successfully to the server was 8 milliseconds ago.
 Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.

Could this be because of the always open database connection? I test the application only for short times. It will run on 4 computers all day long. Can I expect this error more often then? The connection is used every few minutes, so it should be more performant to keep it open, but maybe during break it is not used for half an hour.

What would you recommend me to do? Always reopen the connection or keep it like it is and find a workaround when I get this error? Do you maybe have another idea why this error appears?

Just ask if you need more error log, database code or whatever you need.

Thanks!

Upvotes: 2

Views: 2360

Answers (1)

Pilot824
Pilot824

Reputation: 31

I'm going to say yes, your issue is probably due to the fact that you have a persistent connection open.

I took over a website a while ago and the guy before me had the same idea: Open a single connection, send the queries through it when needed, and never close it. A month after I took over the site, the database wouldn't return any more query results just like this.

As a general rule of thumb and for good programming practice, always clean up after yourself. If you're not using a variable, set it to null and delete it. Not using a connection? Terminate it. This is way less prominent in Java than it is in C++ as Java does all the cleaning up for you for the most part.

Upvotes: 3

Related Questions