"Effective Java Chinese version 2nd edition" study note 7th: Avoid using the finalization method

Source: Internet
Author: User
Tags finally block stack trace terminates

In Java, when an object becomes unreachable, the garbage collector reclaims the storage space associated with the object. Use the try-finally block to reclaim other non-memory resources.

The disadvantage of an end method is that it cannot be guaranteed to be executed in a timely manner. From the beginning of an object becoming unreachable, to its finalization method being executed, the time spent is arbitrarily long. This means that time-focused tasks should not be done by the finalization method. For example, it is an error to use the finalization method to close a file that is already open, because the descriptor of the open file is a very limited resource. Because the JVM delays the execution of the finalization method, a large number of files remain open and may fail to run when a program cannot open the file again.

Executing the finalization method in a timely manner is a major feature of the garbage collection algorithm, which varies greatly from one JVM implementation to another. If the program relies on the point at which the finalization method is executed, the behavior of the program may behave differently in different JVMs. A program runs very well on its own JVM platform for testing, and may not work on the client's JVM platform at all.

The Java language specification does not guarantee that the finalization methods will be executed in a timely manner, and that they are not guaranteed to be executed at all. When a program terminates, the finalization method on some objects that are already inaccessible may not be executed at all. Therefore, you should not rely on the finalization method to update important persistent states. For example, relying on an endpoint method to release a permanent lock on a shared resource, such as a database, can easily overwhelm the entire distributed system.

The two methods of System.GC and system.runfinalization, while increasing the chances of the finalization method being executed, do not guarantee that the finalization method will be executed. The two methods of System.runfinalizersonexit and his twin runtime.runfinalizersonexit, although claiming to ensure that the finalization method was executed, had fatal flaws that had been discarded.

If an uncaught exception is thrown out during finalization, the exception is ignored and the object's finalization process terminates. In other words, if an exception occurs in the finalization method, it does not cause the thread to terminate, nor does it print a stack trace or even print a warning.

There is a serious (Severe) performance penalty for using the finalization method. In other words, increasing the finalization method slows down processing.

If a resource encapsulated in a class's object (such as a file or a thread) needs to be terminated, simply provide an explicit termination method and require that the client of that class call this method when each instance is no longer available. Where the explicit termination method must be recorded in a private domain, "the object is no longer valid." If the terminating method is called after the object has been terminated, the other method must check the field and throw a IllegalStateException exception. An explicit finalization method is often used in conjunction with the try-finally structure to ensure timely termination. An explicit termination method is called inside the finally clause to ensure that the terminating method executes even if an exception is thrown when the object is used.

  

There are two legitimate uses of the finalization method.

First use: When the owner of an object forgets to call an explicit termination method, the finalization method can act as a "safety net (safety net)", and it is better to release the critical resources later than never to release them.

Second use: The local peer (native peer) is a local object (native objects), and a normal object is delegated to a local object by means of the local method (native). Because the local peer is not a normal object, the garbage collector will not know it and will not be recycled when its Java peer is recycled. The finalization method reclaims the local peer if it does not have a critical resource. If the local peer has a resource that must be terminated in a timely manner, the class should have an explicit termination method. The terminating method can be a local method, or it can call a local method.

"End method chain (finalizer chaining)" is not automatically executed. If the class (not object) has an finalization method, and the subclass overrides the finalization method, the child class's finalization method must call the superclass's finalization method manually. The subclass is terminated in a try block, and the end method of the superclass is called in the corresponding finally block. Guarantees that the superclass's finalization method will be executed even if the subclass's finalization process throws an exception.

 1   @Override  2  protected  void  Finalize () throws   Throwable { 3  try   { 4  ... //  terminating subclass State  5 } finally   { 6  super . Finalize (); //  7  }  8  }

  In summary, do not use the finalization method unless you are a security net, or if you are terminating non-critical local resources.

Resources

"Effective Java Chinese version 2nd edition" p24-27

"Effective Java Chinese version 2nd edition" study note 7th: Avoid using the finalization method

Related Article

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.