In Joshua Bloch's book "Effective Java" item 7 second edition he advises to avoid using finally statements particularly for closing files he says "it is a grave error to depend on a finaliser to close files". Two pages later he says that one of the two use cases where it is a legitimate is in the explicit termination method pattern
Foo foo = new Foo();
try{
///process foo
} finally{
foo.terminate();
}
Classes that have a termination method include FileInputStream and FileOutputStream. So wouldn't that mean closing a file in a finally statement?
1) Is Joshua Bloch's Item 7 contradictory?
2) Is the termination method pattern needed? Can't you write the code above without a finally statement that will have the same effect?
I guess that the author meant that you should use a finally
block code (this is not a finalizer) in try-catch
to close/clean your resources instead of relieving on finalize
method (this is a finalizer).
For more info about finalizers check When is the finalize() method called in Java?