Tuesday, September 11, 2007

Resource Release

The vast majority of resources used in Java programs are objects, and garbage collection does a fine job of cleaning them up. On the other hand, nonmemory resources like file handles and socket handles must be explicitly released by the program, using methods with names like close(), destroy(), shutdown(), or release(). If our application involves releasing multiple resources, such as in case of Database operations ( where we need to release ResultSet,Statement,Connection ), we usually follow the below approach.

public void enumerateFoo() throws SQLException {
Statement statement = null;
ResultSet resultSet = null;
Connection connection = getConnection();
try {
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM Foo");
// Use resultSet
}
finally {
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
connection.close();
}

}
This may fail to release all resources if there is any problem while releasing "resultSet", "statement" objects.
To avoid this we can wrap each release operation in a try/catch block as shown below.
public void enumerateBar() throws SQLException {
Statement statement = null;
ResultSet resultSet = null;
Connection connection = getConnection();
try {
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM Bar");
// Use resultSet
}
finally {
try {
if (resultSet != null)
resultSet.close();
}
finally {
try {
if (statement != null)
statement.close();
}
finally {
connection.close();
}
}
}
}

private Connection getConnection() {
return null;
}

No comments: