I need to clarify some things about how Java deals with unwanted objects. As part of my 'Teach myself Java from wherever I can learn it' course, I have created a library method that returns a ResultSet object:
package libfunc;
.
.
public ResultSet getRecordset(String pSQL) throws Exception {
ResultSet retVal = null;
Statement st;
try {
st= con.createStatement();
retVal = st.executeQuery(pSQL);
} catch (Exception e) {
logFile.writeLog(Level.SEVERE, pSQL + "\n" + e);
throw e;
}
return retVal;
}
After gaining a little more knowledge I thought that this may be a better way of doing things:
public ResultSet getRecordset(String pSQL) throws Exception {
ResultSet retVal = null;
try (Statement st= con.createStatement()) {
retVal = st.executeQuery(pSQL);
} catch (Exception e) {
logFile.writeLog(Level.SEVERE, pSQL + "\n" + e);
throw e;
}
return retVal;
}
However, after making the change, the following code in the calling method fails, telling me that the Resultset object is already closed:
package someApp;
.
import libfunc;
.
sql = "select * from a_table";
try (ResultSet rsT = libfunc.getRecordset(sql)) {
while (rsT.next()) {
Object[] rowdata = { rsT.getString("field1"), rsT.getString("field2"), rsT.getInt("uid") };
model.addRow(rowdata);
}
} catch (Exception e) {
some code
}
At this point I realised that the returned Resultset object needs the Statement object (st, that is automatically discarded after the try{} block in the second library snippet) to stay alive, hence the original code must stay.
This leaves me wondering - after I've finished with the Resultset, what happens to the Statement object that I created in the library? Does it automatically cease to exist when the Try{} of the calling method is finished?
It is feasible that there are several calls to the same library method, potentially leaving several Statement objects - how can I be certain that I'm not leaving behind any stray objects that will fill up usable memory?
I also call dispose() when I close the Frame that displays the data but am uncertain if that would deal with all the underlying objects.