Object lives on after going out of scope
When you reassign the reference variable to another object, the object previously referenced still lives on in memory. Their close
method is not called.
If not otherwise referenced elsewhere, the orphaned object will become a candidate for garbage collection. But garbage collection does not call the object’s close
method.
try-with-resources
You should learn to use try-with-resources syntax to automatically close resources such as JDBC objects, file I/O objects, etc. See tutorial by Oracle. Close such resources as soon as possible, as soon as you are done with them.
Example code
Your code should look something like following example code. Notice how each JDBC object is closed immediately after we finish using it: Connection
, PreparedStatement
, and ResultSet
.
A DataSource
object does not get closed as it is not actually “open”. A DataSource
object merely holds information needed to connect to database (server address, user name, password, etc.).
String[] queries = new String[ 10 ];
// … populate queries array.
DataSource dataSource = this.fetchDataSource();
try (
Connection conn = dataSource.getConnection() ;
)
{
for ( int i = 0 ; i < 10 ; i++ )
{
try (
PreparedStatement ps = conn.prepareStatement( queries[ i ] , Statement.RETURN_GENERATED_KEYS ) ;
)
{
ps.setObject( 1 , LocalDate.of( 2021 , Month.JANUARY , 23 ) );
int countOfRowsAffected = ps.executeUpdate();
if ( countOfRowsAffected > 0 )
{
try ( ResultSet rs = ps.getGeneratedKeys() ; )
{
while ( rs.next() )
{
// … process your keys.
}
}
// The `ResultSet` object is auto-closed by this point.
}
}
// The `PreparedStatement` object is auto-closed by this point.
}
} catch ( SQLFeatureNotSupportedException e )
{
e.printStackTrace();
} catch ( SQLTimeoutException e )
{
e.printStackTrace();
} catch ( SQLException e )
{
e.printStackTrace();
}
// The `Connection` object is auto-closed by this point.
An extra benefit of using try-with-resources is that your intentions are quite clear. Anyone reading your code knows where you intend to dismiss each resource.