(Item 6) Avoid finalizer
1) Java Language Specification provide no guarantee that finalizer will get executed.
2) Nothing time-critical should ever be done in finalizer (e.g. close file)
3) Don’t seduced by System.gc and System.runFinalization, they don’t guarantee the finalizer get executed
4) System.runFinalizationOnExit(or Runtime.runFinalizationOnExit) claim to guarantee finalization but those method are fatally flawed and have been deprecated
5) An uncaught exception will be ignored in finalize()
6) Provider a explicit method for termination and require client of class invoke it. (e.g. InputStream.close() is such a termination method)
7) Combine termination method with try-finally block
8)what are finalize() good for?
a) Last safety net
b) For “native peer”, (e.g. invoking C++ new() to create object, then you can call delete in finalizer)
9)finalizer chaining
// Manual finalizer chaining
protected void finalize() throws Throwable {
try {
// Finalize subclass state
...
} finally {
super.finalize();
or use finalizer guardian inner class, you need not call super.finalize()
// Finalizer Guardian idiom
public class Foo {
// Sole purpose of this object is to finalize outer Foo object
private final Object finalizerGuardian = new Object() {
protected void finalize() throws Throwable {
// Finalize outer Foo object
...
}
};
... // Remainder omitted
}