Close in the same method you open in if at all possible. Consistently doing this makes it easy for code-reviewers and maintainers to easily triage resources into (obviously freed, obviously problematic, and needs more attention).
A few other notes:
- Use
try (...)
or do the closing in finally
so the resource is closed even when the code using it fails with an exception.
- Use the
@WillClose
and @WillNotClose
annotations as appropriate so that IDEs and tools like findbugs can point out problems.
public void mainTest(){
List<?> list;
try (ResultSet rs = pstmt.executeQuery(query)) {
list = populateRS(rs);
}
// work with list
}
public List<?> populateRS(@WillNotClose ResultSet rs){
//work with result set
}
or if you're stuck with older Java:
public void mainTest(){
List<?> list;
ResultSet rs = pstmt.executeQuery(query);
try {
list = populateRS(rs);
} finally {
if(rs!=null)rs.close();
}
// work with list
}