Finalizers are unpredictable, usually dangerous, and generally not needed. There are some effective ways to use it, but basically it is better not to use it.
The finalize () method. The finalize () method is defined in the java.lang.Object class, which is the inheritance source for all classes in the Java language. That is, every class has a finalize () method. A method called when the garbage collector runs.
A native object that a regular object delegates through a native method. Since it is not a regular object, the garbage collector is unaware and cannot retrieve the native peer when the regular object is retrieved.
If a class has a finalizer and a subclass overrides it, the finalizer for that subclass must manually call the finalizer for the superclass (Example 2).
If a subclass implementor overrides a superclass finalizer and forgets to call the superclass finalizer, the superclass finalizer will never be called. Finalizer guardians are effective in protecting against such careless or malicious subclasses (Example 3).
Example 1
//Try to guarantee execution of termination method-finally block
Foo foo = new Foo(...);
try {
//Do what you have to do with foo
...
} finally {
foo.terminate(); //Explicit termination method
}
Example 2
//Manual finalizer chain
@Override protected void finalize() throws Throwable {
try {
... //Subclass finalizer processing
} finally {
super.finalize();
}
}
Example 3
//Finalizer Guardian idiom
public class Foo {
//The sole purpose of this object is to finalize the outer Foo object
private final Object finalizerGuardian = new Object() {
@Override protected void finalize() throws Throwable {
... //Finalize the outer Foo object
}
};
... //The rest is omitted
}
• Time constraints should not be done in the finalizer, as the time it takes for the finalizer to run can be any length of time. · Never rely on finalizers to update critical persistent states
Creating and releasing objects with finalizers is about 430 times slower than objects without them
-Provide an explicit termination method (Example 1) · Explicit termination methods are often used with try-finally syntax to guarantee termination
[Read Effective Java] Chapter 3 Item 8 "When overriding equals, follow the general contract" https://qiita.com/Natsukii/items/bcc5846dbfa69bfda9b0
Recommended Posts