Effective seventh of Java learning notes--Avoid using the finalization (finalizer) method

Source: Internet
Author: User
Tags terminates

Avoid using the finalization method (finalizer)

The finalization method (finalizer) is often unpredictable and dangerous, and is generally unnecessary.

Do not think of finalizer as a counterpart to destructors in C + +. In Java, when an object is unreachable (that is, when there is no reference to the object), the memory resource associated with the object is reclaimed by the garbage collector, while other memory resources are typically done by the try-finally code block.

First, the shortcomings of finalizer:

1. The disadvantage of the finalization method is that it cannot be guaranteed to be implemented in a timely manner.

Timely execution of the finalizer method is a major feature of the JVM garbage collection method. Because the garbage collection algorithms of different JVMs are different, the JVM will "unintentionally" defer execution of the finalization method, so the execution time point of the finalization method is very unstable.

The 2.finalizer method has a lower thread priority than other threads in the current program, and the Java language specification does not guarantee which thread can execute the finalizer method.

The 3.JAVA language specification does not guarantee the timely execution of the finalizer method, and does not guarantee that the finalizer method will be enforced. When the program terminates, it is possible that some of the object's finalizer methods have not been executed. --You should not rely on the finalizer method to update important persistent states.

4.SYSTEM.GC and system.runfinalization do not guarantee that finalizer must be executed.

5.system.runfinalizersonexit Runtime.runfinalizersonexit can guarantee that finalizer must be executed, but these two methods have been deprecated.

6. If an uncaught exception is thrown out of the finalizer method, the exception can be ignored (the warning is not printed), and the finalizer method terminates. This exception causes the object to be in a "corrupted" state, and an indeterminate behavior can occur if another thread is to use the object.

7.finalizer method can have very serious (Severe) performance loss

Second, how to implement the termination of object resources in thread without finalizer method?

Use the display termination method.

Show the requirements for the termination method:

1. The instance must record whether it has been terminated.

2. The display termination method must be recorded in a private domain "the object is no longer valid"

3. After executing the Terminate method, when executing the other method of the object, check that the "object is no longer valid" private domain, throwing illegalstateexception.

Examples of display termination methods:

1.InputStream

2.OutputStream

3.java.sql.connection

4.java.util.timer

Shows how to use the termination method: typically used with try-finally to ensure timely termination.

FileInputStream FileInputStream = new FileInputStream ();

try{

Do something about FileInputStream;

}finally{

Fileinputstream.close ();

}

Third, the lawful use of the end method.

1. As a safety net--show termination method when you forget to call

2. Terminating non-critical local resources (in Android JNI operations)

Iv. in the execution of the finalization method, ensure that if an exception occurs during the finalization of the subclass, the end process of the superclass will be executed.

Because the end method chain does not execute automatically, we need to ensure this manually.

Method One: Use the TRY–FINALIZE code structure

@Override
protected void Finalize () throws Throwable {
try{
.....//finalize Subclass State
} finally {
Super.finalize ();
}
}

Method Two: Use Finalizer Guardian (end method Guardian)

Class A {

End Guardian
Private Final Object Finalizerguardian = new Object () {

@Override
The end method of the end Guardian will be executed
protected void Finalize () {

Finalizer this outer class--a
System.out.println ("A Finalize by the Finalizerguardian");
}
};

Anyway

1. Do not use the finalization method unless you are working as a safety net or to end non-critical local resources.

2. If you really need to, you can use the display termination method

2. If there is no way to really use finalize, don't forget to call Super.finalize (). You can also consider whether to use the End method Guardian so that the finalization method of the parent class of the class that does not call the Super.finalize () method is also executed.

Resources:

"Effective Java second Edition"

Effective seventh of Java learning notes--Avoid using the finalization (finalizer) method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.