Java Finalize method

Source: Internet
Author: User

Programmers are aware of the importance of initialization, but often forget the same important cleanup effort. After all, who needs to clear an int? However, when using a library, it is not always safe to "discard" an object after it has been exhausted. Of course, Java has a garbage collector to reclaim memory resources that are occupied by useless objects. But there is also a special case: Suppose your object (not using new) obtains a "special" area of memory, because the garbage collector only knows to release the memory allocated through new, so it does not know how to release this "special" Memory of the object.

To cope with this situation, Java allows you to define a method named Finalize () in the class. It works "should" be like this: once the garbage collector is ready to release the storage space occupied by the object, its finalize () method is called first, and the memory occupied by the object is actually reclaimed when the next garbage collection action occurs. So if you're going to use Finalize (), you can do some important cleanup at "garbage collection time."

There is a potential programming trap because some programmers (especially C + + programmers) may mistakenly consider Finalize () as a "destructor" in C + + (the function must be used to destroy objects in C + +). So it is necessary to make a clear distinction: in C + +, objects are bound to be "destroyed" (if there are no errors in the program), while Java objects are not always "garbage collected". Or in other words:

1. Objects may not be recycled.

2. Garbage collection does not equal "destruction."

Keep this in mind and you'll be able to stay out of trouble. This means that if you have to perform certain actions before you no longer need an object, you have to do it yourself. Java does not provide a "destructor" or a similar concept, to do similar cleanup work, you must create a common way to perform cleanup work yourself. For example, suppose an object is drawn to the screen during the creation process. If you do not explicitly erase it from the screen, it may never get erased. If the

Finalize () adds some sort of erase function, and when "garbage collection" occurs (not guaranteed to happen), Finalize () gets called and the image is erased. If "garbage collection" does not occur, the image will remain intact.

Perhaps you will find that as long as the program is not on the verge of storage space to run out of the moment, the object occupies the space will always be not released. If the program execution finishes and the garbage collector has not freed up storage space for any objects you create, the resources are all returned to the operating system as the program exits. This strategy is appropriate because the garbage collection itself has a cost, and if you don't use it, you don't have to pay for that part of the cost.

What is the purpose of finalize ()?

At this point, you have learned that finalize () should not be used as a generic purge method. So what is the real purpose of finalize ()?

This leads to the 3rd to remember:

3. Garbage collection is only related to memory.

In other words, the only reason the garbage collector exists is to reclaim memory that the program is no longer using. So for any behavior related to garbage collection (especially the Finalize () method), they must also be related to memory and its recycling.

But does this mean that if the object contains other objects, finalize () should explicitly release those objects? No-regardless of how the object is created, the garbage collector is responsible for releasing all memory occupied by the object. This limits the need for Finalize () to a special case: you allocate storage space for an object in a way that is not "created". But, as you can see, everything in Java is an object, what about this particular situation?

There seems to be a finalize () because you might be allocating memory in a similar way to C rather than the usual practice in Java. This happens mainly when using a "local method", which is a way to invoke non-Java code in Java. Local methods currently only support C and C + +. But they can invoke code written in other languages, so you can actually invoke any code. In non-Java code, you might call a C-like malloc () function to allocate storage space, and unless you call the free () function, the storage space will not be freed, resulting in a memory leak. Of course, free () is a function in C and C + +, so you need to call it in Finalize () with a local method.

At this point, you may have learned not to use Finalize () too much. Yes, it's really not the right place to do normal cleanup work. So, where should the normal cleanup work be performed?

You must perform the purge

To clear an object, the user must call the method that performs the purge action at the time of the purge. It sounds simple, but it is slightly inconsistent with the concept of "destructor" in C + +. In C + +, all objects will be destroyed, or "should" be destroyed. If a local object is created in C + + (which is not in Java on the stack), the Destroy action occurs at the end of the object scope, which is bounded by the "right curly brace". If the object is

Created with new (similar to Java), the destructor is called when the programmer calls the C + + DELETE (Java does not have this command). If the programmer forgets, the destructor is never called, and a memory leak occurs, and the rest of the object is not purged. This error is difficult to track, which is a major factor in turning C + + programmers into Java.

Instead, Java does not allow the creation of local objects, you must use new. In Java, there is also no "delete" to free objects, because the garbage collector helps you free up storage space. It is even superficial to think that it is due to the existence of garbage collection mechanisms that Java does not have destructors. However, as you learn, you will understand that the existence of a garbage collector is not a complete substitute for a destructor. (And you absolutely cannot call finalize () directly, so this is not an appropriate

Way. If you want to do cleanup beyond freeing up storage space, you still have to explicitly invoke an appropriate Java method. This is equivalent to the use of destructors, and it is not convenient.

Remember that neither "garbage collection" nor "end" is guaranteed to happen. If the Java Virtual Machine (JVM) is not running out of memory, it will not waste time reclaiming garbage to recover memory.

End condition

Typically, you cannot expect finalize (), you must create additional "purge" methods and explicitly invoke them. It seems that finalize () can only exist in obscure usages that programmers find difficult to use. However, Finalize () has an interesting usage, and it does not rely on a call to finalize () every time, which is the validation of the object "end condition".

When you are no longer interested in an object, that is, it can be cleared, the object should be in a certain state so that the memory it occupies can be safely freed. For example, if an object represents an open file, the programmer should close the file before the object is recycled. As long as there are parts of the object that are not properly cleared, your program has a very cryptic error. The value of Finalize () is that it can be used to eventually discover this situation, although it is not always called. If one time

Finalize () action makes the bug discoverable, so you can find out where the problem is-and that's what you really care about.

Here's a simple example of how you might use it:

Class Book {Boolean checkedout = false;   Book (Boolean checkOut) {  checkedout = CheckOut;  } void CheckIn () {checkedout = false;   } public void Finalize () {if (checkedout)  System.out.println ("error:checked out");  Normally, you'll also do this://super.finalized (); }} public class Terminationcondition {public static void main (string[] args) {book  novel = new book (true); 
   //Proper cleanup:  Novel.checkin ();  Drop the reference, forget to clean up:  new book (true);  Force garbage Collection & finalization:  System.GC (); }  }

The end condition of this example is that all book objects should be checked in (check in) before being garbage collected. But in the main () method, a book was not checked in because of a programmer's error. This error will be difficult to detect without finalize () to verify the termination criteria.

Note that System.GC () is used to force the finalization of the action. Even if you do not, you can eventually find the wrong book object by repeating the execution of the program (assuming that the program will allocate a large amount of storage space leading to the execution of the garbage collection Action).

Reference: http://www.java3z.com/cwbwebhome/article/article8/83463.html?id=4388

Java Finalize 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.