Java---the difference between final, finally, Finalize

Source: Internet
Author: User
Tags finally block

 the Java Finalize method usestags: JAVAAPPLETOBJECTWIZARDJVM Work2011-08-21 11:37 48403 People read comments (5) favorite reports Classification:Java (+)

"JAVA programming ideas":

Java provides the finalize() method, which is called Finalize () when the garbage collector prepares to release memory.

(1). objects are not necessarily recycled.

(2). garbage collection is not a Destructor.

(3). garbage collection is only related to Memory.

(4). garbage collection and finalize () are unreliable, as long as the JVM is not running out of memory to the point where it will not waste time on garbage collection.

Sometimes when you undo an object, you need to do something. For example, if an object is processing a non-java resource, such as a file handle or a window character font, then you want to make sure that the resources are freed before an object is Undone. To deal with this situation, Java provides a mechanism known as the closing (finalization). With this mechanism you can define special operations that are performed when an object is about to be released by the garbage Collector.

To add the finishing touches to a class (finalizer), you just define the finalize () Method. This method is called when Java recycles an object of the class. In the Finalize () method , you specify the action that must be performed before an object is undone . garbage Collection runs periodically, checking that objects are no longer referenced by a running state or indirectly through other objects. Just before the object is freed, the Java runtime calls the Finalize () method of the Object.

The general format of the Finalize () method is as Follows:

protected void Finalize ()
Finalization code here

Where the keyword protected is to prevent code that is defined outside the class from accessing the Finalize () Identifier. The identifier and other identifiers are explained in chapter 7th.

It is important to understand that finalize () is called just before garbage Collection. For example, finalize () is not called when an object is outside its scope. This means you can't know when--or even if--finalize () is Called. therefore, your program should provide other ways to release the system resources used by the object and not rely on finalize () to complete the normal operation of the Program.

Note: If you are familiar with c, then you know that C allows you to define an undo function (destructor) for a class that is called before the object is out of Scope. Java does not support this idea nor does it provide undo Functions. The Finalize () method is only close to the function of the undo Function. When you have a lot of experience with java, you will see that because Java uses the garbage collection subsystem, there is little need to use undo Functions.

Understand Finalize()-substitute for destructor

by Tim Gooch

In many ways, Java is similar to C + +. Java's syntax is very similar to C++,java with classes, methods, and data members; Java classes have constructors; Java has exception handling.

however, If you have used C + + you will find that Java also loses some of the features that may be familiar to You. One of these characteristics is the Destructor. Instead of using destructors, Java supports the finalize () Method.

In this article, we will describe the difference between finalize () and C + + Destructors. In addition, we will create a simple Applet to demonstrate how finalize () works .

The ultimate limit

Unlike Java, C + + supports local objects (stack-based) and global objects (heap-based). Because of this dual support, C + + also provides automatic construction and destruction, which leads to calls to constructors and destructors, which are allocations and releases of memory (for heap objects).

In Java, all objects reside in heap memory, so local objects do not Exist. As a result, Java designers felt no need for destructors (as implemented in C + +).

instead, Java defines a special method called Finalize (), which provides some of the functions of the C + + Destructor. however, Finalize () is not exactly the same as a C + + destructor, and can be assumed to cause a series of problems. A key element of the Finalize () method is the Java garbage collector.

Garbage collector

In C + +, pascal, and several other programming languages, developers have a responsibility to play an active role in memory Management. For example, If you allocate memory for an object or data structure, you must free that memory when you no longer use it.

In java, when you create an object, the Java Virtual machine (JVM) allocates memory for the object, calls the constructor, and starts tracking the object you are Using. When you stop using an object (that is, when there is no valid reference to the object), the JVM marks the object as disposed by the garbage Collector.

When the garbage collector is about to release the memory of an object, it calls the Finalize () method of the object, if the object defines this Method. The garbage collector runs in a stand-alone, low-priority manner, and only when other threads are suspended waiting for the memory to be released, does it begin to run the memory that freed the Object. (in fact, You can call the System.GC () method to force the garbage collector to release memory for these Objects.) )

In the above description, there are some important things to be aware of. first, Finalize () is performed only when the garbage collector frees the Object's memory. If the garbage collector does not free memory before the Applet or application exits, the garbage collector will not call finalize ().

second, unless the garbage collector considers that your Applet or application requires additional memory, it does not attempt to free the memory of objects that are no longer in Use. In other words, this is entirely possible: an Applet allocates memory to a small number of objects without causing serious memory requirements, so the garbage collector exits without releasing the memory of those Objects.

obviously, If you define a finalize () method for an object, the JVM might not call it because the garbage collector has not freed the memory of those Objects. Calling System.GC () does not work either, because it simply gives the JVM a recommendation rather than a command.

What are the advantages of finalize ()?

If finalize () is not a destructor, the JVM does not necessarily call it, and you may wonder if it will benefit in any Case. In fact, it doesn't have much merit in Java 1.0.

According to the Java documentation, Finalize () is a method for releasing Non-Java Resources. however, The JVM has a large likelihood of not invoking the Finalize () method of the object, so it is difficult to justify the use of this method to release Resources.

Java 1.1 solves this problem in part by providing a system.runfinalizersonexit () method. (do not confuse this method with the System.runfinalizations () method in Java 1.0.) Unlike the System.GC () method, the System.runfinalizersonexit () method does not immediately attempt to start the garbage collector. instead, when an application or Applet exits, it invokes the Finalize () method for each Object.

As you might guess, forcing the garbage collector to clear the memory of all stand-alone objects by calling the System.runfinalizersonexit () method can cause noticeable delays when the code is cleared for Execution. Now create a sample Applet to demonstrate how the Java garbage collector and finalize () methods Interact.

Recycling waste

Start by using the Java applet Wizard to create a new Applet. When prompted to do so, enter final_things as the Applet name and choose not to generate source file Comments.

next, in the Java Applet Wizard, take the third step and do not select the multithreading Option. Before the fifth step, modify the description of the Applet as Needed.

When you click finish, the Applet Wizard will generate a new workspace and create a default Java file for the Project. Select the appropriate code input from list A (we have highlighted the code you need to enter).

When you have finished entering the code, configure your Internet browser to write the output information of System.out to the Javalog.txt file. (select Java Logging in the Advanced page of the IE Options dialog box.) )

Compile and run the Applet. then, wait for the applet to run (you will see the information that the applet has started in the status bar), exit the browser, and open the Javalog.txt file. You will find information similar to the following lines:

Things constructed

0 things finalized

As you can see, the creation of 1,000 objects still does not force the garbage collector to start reclaiming space, even if the Applet exits without objects being used.

now, Delete the comment in the first line of the stop () method to use the System.GC () method. Compile and run the applet again, wait for the applet to finish running, and exit the Browser. When you open the Javalog.txt file again, you will see the following line:

Things constructed

963 things finalized

This time, the garbage collector thinks most objects are not being used and recycles them. In order, the JVM invokes their finalize () method when the garbage collector starts releasing memory for these Objects.

Inherit Finalize ()?

By the way, if you define finalize () in the class, it will not automatically call the methods in the base class. After we have discussed the differences between Finalize () and C + + destructors, This conclusion will not be surprising, as the cleanup code that is customized for a class does not necessarily need to be in another class.

If you decide to call the Finalize () method in the base class by deriving a Class's finalize () method, You can handle it like any other inherited method.

protected void Finalize ()


Super.finalize ();

Other finalization code ...


In addition to allowing you to control whether or not to perform a purge operation, This technique also allows you to control when the finalize () method of the current class Executes.


however, the benefit is that Java's automatic garbage collector does not lose balance. As a convenience, you have to give up control over the release of system Resources. Unlike destructors in C + +, Java applets do not automatically execute the Finalize () method in your class. In fact, if you are using Java 1.0, even if you try to force it to call the finalize () method, there is no guarantee that it will be called.

therefore, you should not rely on finalize () to perform resource cleanup work for your applets and applications. instead, you should explicitly clear those resources or create a try...finally block (or similar mechanism) to Implement.

The Finalize method is related to the garbage collector in Java programming. That is, when an object becomes a garbage object, if the Object's memory is recycled, then the Finalize method defined in the system can be called to complete

of course, the memory recycling of Java can be done by the JVM from the Start. If you use it manually, you can use the method Above.

To Illustrate:

[java]View PlainCopyprint?
  1. Public class Finalizationdemo {
  2. public static void main (string[] Args) {
  3. Cake C1 = new Cake (1);
  4. Cake C2 = new Cake (2);
  5. Cake C3 = new Cake (3);
  6. C2 = C3 = null;
  7. System.GC (); //invoke the Java garbage collector
  8. }
  9. }
  10. Class Cake extends Object {
  11. Private int id;
  12. public Cake (int Id) {
  13. = id;
  14. System.out.println ("Cake Object" + ID + "is created");
  15. }
  16. protected void Finalize () throws java.lang.Throwable {
  17. super.finalize ();
  18. System.out.println ("Cake Object" + ID + "is disposed");
  19. }
  20. }

Results run:
[java]View PlainCopy print?
    1. C \1>java Finalizationdemo
    2. Cake Object 1is created
    3. Cake Object 2is Created
    4. Cake Object 3is Created
    5. Cake Object 3is disposed
    6. Cake Object 2is disposed


Modifier (keyword) If a class is declared final, it means that it can no longer derive a new subclass and cannot be inherited as a parent class. therefore, A class cannot be declared abstract and declared Final. Declaring variables or methods as final ensures that they are not changed in Use. A variable declared as final must be given an initial value at the time of declaration, and can only be read in subsequent references and cannot be modified. The method that is declared final is also used only and cannot be overloaded.


Provides a finally block to perform any cleanup operations when exception handling Occurs. If an exception is thrown, the matching catch clause executes, and the control enters the finally block, if Any. General exception handling blocks are Required.


The method Name. Java technology allows the use of the Finalize () method to do the necessary cleanup before the garbage collector clears objects from Memory. This method is called by the garbage collector to this object when it determines that the object is not Referenced. It is defined in the Object class, so all classes inherit it. Subclasses override the Finalize () method to organize system resources or perform other cleanup Work. The Finalize () method is called on the object before the object is deleted by the garbage Collector.

All classes in Java inherit the Finalize () method from the object class.

When the garbage collector (garbage Colector) decides to reclaim an object, it runs the Finalize () method of the Object. It is worth the attention of C + + programmers that the Finalize () method is not equivalent to a destructor. There is no destructor in Java. A C + + destructor is run when the object Dies. Because C + + does not have garbage collection, object space is recycled manually, so the programmer should delete () the object once it is not available. So in the destructor often do some file preservation and other finishing Work. But unfortunately in java, if the memory is always sufficient, then garbage collection may never happen, that is, filalize () may never be executed, and it is obvious that it is unreliable to expect it to do the finishing Work.

So what exactly does finalize () do? Its main purpose is to reclaim the memory of special channel Applications. Java programs have garbage collector, so in general memory problems don't bother Programmers. But there is a jni (Java Native Interface) called Non-java program (c or C + +), and finalize () works to reclaim this part of Memory.

Java---the difference between final, finally, Finalize

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: 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.