Let’s say I get a PreparedStatement from a Connection object, and then later I overwrite the reference with another PreparedStatement. Then, later, I close() the reference. Will the first PreparedStatement (the one I lost the reference to) remain open? Or does some protocol or garbage collection take care of that?
For example:
PreparedStatement ps = connection.prepareStatement(MY_QUERY);
// do stuff
ps.execute();
ps = connection.prepareStatement(MY_OTHER_QUERY);
// do stuff
ps.execute();
ps.close();
Does the first PreparedStatement object, the one used to execute MY_QUERY, remain open?
Yes, the
PreparedStatementwill be left open until it gets garbage collected* (if at all).That’s why you always see the rule to always release (close) external resources that you acquire.
JDBC resources (such as this prepared statement, connections, results sets) and IO resources (sockets, streams, …) are the two most common resources that you manually need to manage in Java.
* strictly speaking it could be closed in the
finalizemethod which could be slightly before it gets GCed, but after it becomes eligible for the GC, but for this discussion this is close enough.