finalize()
Unlike C++
destructors in methods, destructors C++
must be used to free memory and resources. In Java
, memory is usually reclaimed by GC (garbage collector), and resources are often used try...finally
to complete.
Disadvantages of using the finalize method
not guaranteed to be executed
1). The program is forcibly terminated, and the
finalize
method will not be called.
2).finalize
An exception is thrown when the method is executed, and the execution will not continue.Timely execution cannot be guaranteed
1). Time-sensitive tasks cannot be
finalize
executed in , such as file resource recoveryperformance loss
- Poor portability
1). DifferentJVM
implementations may not work onGC
differentfinalize
platforms
Fair use
Safety Net - Last Release Memory and Resource Guarantee
When an object user forgets totry...finaly
explicitly free resources,finalize
methods can be used as a last resort (probably better than never). For exampleFileInputStram
, methods in ,FileOutputStram
,Timer
,Connection
etc.finalize
Recycle local peer
Local peer: Refers to an object that delegates an ordinary object to a local object
Java
by calling a local method.JNI
Local peers cannot beJVM GC
recycled.GC
Recycling can be passed when the local peer does not have critical resources , otherwise it is better to show termination.
When using the finalize
method, it should be noted that if the subclass overrides the finalize
method of the parent class, the subclass will not call the finalize
method of the parent class by default . You need to display the call like this:
@Override
public void finalize() throws Throwable {
try {
//子类的finalize实现
} finally {
//调用父类的finalize方法
super.finalize();
}
}
You can also use finalizers with the following code:
public class Parent {
private Object finalizeGuardian = new Object() {
@Override
protected void finalize() throws Throwable {
System.out.println("Parent Guardian finalize");
}
};
private static void testFinalize() {
Sub sub = new Sub();
sub = null;
System.gc();
}
//输出结果为:
//Sub finalize
//Parent Guardian finalize
public static void main(String[] args) {
testFinalize();
}
}
class Sub extends Parent {
@Override
protected void finalize() throws Throwable {
System.out.println("Sub finalize");
}
}
Summarize
- The finalize method is strongly deprecated;
- In case it must be used, note that the subclass must explicitly call the superclass
finalize
method, or use the finalizer guard method