You're right to close your ResultSet
carefully. Leaving those objects around after you finish with them is definitely a way to get memory leaks.
You should also close your Connection
objects when you no longer need them. If your Java program terminates any Connection
objects you still have open are closed, automatically. If no queries are in progress on those objects then the MySQL server closes the connection and cleans up when Java abandons the connection.
Java since version 7 has a way to manage this cleanly. You can do
try (Connection db = DriverManager.getConnection(url,_username,_password)){
//use the connection object
...
try (ResultSet result = stmt.ExecuteQuery(whatever)) {
// use the resultset
} catch (whatever) { whatever }
}
catch(whatever) { whatever }
This is is a nice way to avoid these leaks; the Connection and ResultSet objects get closed automatically at the end of the try / catch block just as if they were closed in a finally{}
clause. It's called automatic resource block management.
Yes, close Connections when you're done with them. If you open a lot of Connection
objects without closing them, two bad things happen:
- Less bad: your Java program's RAM will leak.
- More bad: your MySQL server's connection slots will fill up and it will start rejecting new connections. Client bugs which use up server resources are generally bad bugs.
Failing to close Connections can be pernicious, because typical programs don't use as many of them as ResultSets. So it takes longer to accumulate lots of unclosed connections, and you may not detect the problem while testing. Testers should log into the MySQL server directly and run the SHOW PROCESSLIST;
command during system testing to see if unclosed Connections are accumulating.
Close your ResultSets and your Connections.