7th: Avoid using the finalization method

Source: Internet
Author: User

The finalization method (finalize) is usually unpredictable, and it is not a counterpart of the C + + destructor (destructors), and once the object becomes unreachable in Java, the garbage collector automatically reclaims the storage space associated with that object, without requiring the programmer to do a specific job. C + + destructors can also be used to reclaim other non-memory resources, which in Java are usually done with try-finally.

Disadvantages of the finalization method:

1. Can not be guaranteed to be implemented in a timely manner, time-sensitive tasks should not be completed by the finalization method, such as the end method to close the open file, because the file descriptor is a limited resource, if a large number of files remain open, when the program can no longer open the file, may run failure, and if the file is written to open, At this time the file should not be read or write, only wait for the file to be written closed, to write, to continue to do another operation, if the end method is not executed, then the entire file has been written, but has not closed the case, can not be accessed, greatly reduce performance.

2. Even if the execution of the finalization method is a major function of the recovery algorithm, the use of the finalization method may lose platform independence due to the large phase path implemented by different JVM recovery algorithms.

The 3.Java language specification does not guarantee that the finalization method will be executed, and that when a program terminates, it is entirely possible that the terminating methods of some inaccessible objects are not executed, such as relying on the finalization method to free permanent locks on the database, which may cause the lock to never be freed.

What to do if the resource encapsulated in the object of the class does need to be terminated.

Provides an explicit finalization method. This means that instead of overwriting the Finalize method, we write a method of terminating the resource. For example, the Close method of Java.io.FileInputStream. When you are finished using this FileInputStream object, explicitly call Close () to reclaim the resource.

Benefits of the Finalization method:

1. When the owner of an object forgets to invoke an explicit finalization method, the finalization method can act as a "safety net."

Let's see how FileInputStream did it:

 Public voidClose () throws IOException {synchronized (closelock) {if(closed) {return; } Closed=true; }        if(Channel! =NULL) {channel.close (); } fd.closeall (Newcloseable () { Public voidClose () throws IOException {close0 (); }        });}protected voidFinalize () throws IOException {if(FD! =NULL) && (FD! = FileDescriptor.inch)) {            /*if FD is GKFX, the references in FileDescriptor * would ensure that finalizer are only called when * Safe to do. All references using the FD has * become unreachable. We can call Close ()*/Close (); }}

You can see that the FileInputStream is still covered by the Finalize method, and what you do is call the Close method, so that when the object holder forgets to call the Close method, it calls close in the Finalize method, which is the "safety net" The meaning.

2. Keeper of the method of termination. Put the finalization method in an anonymous class whose only purpose is to end its perimeter instance. The perimeter instance holds the only instance of the guardian of the terminating method, which means that when the perimeter instance is unreachable, the endpoint keeper is unreachable, and the garbage collector reclaims the instance of the end method Guardian while recovering the perimeter instance. The Finalize method of the gatekeeper of the end method frees the resources of the perimeter instance as if it were a method of terminating the method as a perimeter instance.

Take a look at the end method of Java.util.Timer Guardian:

 Public voidCancel () {synchronized (queue) {thread.newtasksmaybescheduled=false;            Queue.clear ();  Queue.notify (); //In case the queue was already empty.        }}PrivateFinal Object Threadreaper =NewObject () {protected voidFinalize () throws Throwable {synchronized (queue) {thread.newtasksmaybescheduled=false; Queue.notify (); //In case the queue is empty.            }        }};

The Cancel method is the explicit termination method provided by the timer, and Threadreaper is a private variable that guarantees that there is no reference to it except the instance itself, overwriting the Finalize method and implementing the same functionality as the Cancel method.

7th: Avoid using the finalization 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.