[java]final keyword, finally keyword, and finalize () method

Source: Internet
Author: User
Tags finally block

Final keyword:

The final keyword usually refers to "immutable", and the use of "cannot be changed" can be done for two reasons: design or efficiency.

Final can modify variables, methods, and classes.

first, final variables

A domain that is both static and final occupies only a certain amount of storage space that cannot be changed.

When you apply a final adornment to an object reference instead of a base type, its meaning is a bit confusing. For basic types, final causes the values to be constant. For object references, final makes the reference constant. Once a reference is initialized to an object, it cannot be changed to point to another object. However, the object itself can be modified, and Java does not provide a way to keep any object constant (but you can write your own class to achieve a constant effect on the object).

If defined as static, the emphasis is only one copy.

The example above shows the difference between defining a final value as static and non-static. This difference is only displayed when the numeric runtime is initialized.

 second, final method

There are two reasons to use the final method.

1. Lock the method to prevent any inherited classes from modifying its meaning. This is a design consideration: you want to make sure that the method behaves the same in inheritance and is not overwritten.

2. The second reason for the previous recommendation to use the final method is efficiency. In early implementations of Java, if a method was indicated as final, it was agreed that the compiler would convert all calls to the method into inline calls. When the compiler discovers a final method invocation command, it will, according to its own discretion, skip the normal method of inserting the program code and execute the method invocation mechanism (pressing the argument into the stack, adjusting the parameters to the method code and executing, and then returning and cleaning the parameters in the stack, processing the return value), and replace the method call with the copy of the actual code in the method body. This will eliminate the overhead of the call. Of course, if a method is large, your program code expands, so you may not see any performance improvements in the inline because the resulting performance increase is reduced by the amount of time spent in the method.

Final and Private keywords

All private methods in the class are implicitly specified as final. Because the private method cannot be taken, it cannot be overwritten. You can add a final modifier to the private method, but this does not add any extra meaning to the method.

Overwrite occurs only if a method is part of the interface of the base class. That is, you must be able to transform an object up to its base class and call the same method. If a method is private, it is not part of the base class interface. It is only some program code that is hidden from the class, except that it has the same method name.

third, final category

When you define the whole of a class as final, it indicates that you are not going to inherit the class, and you are not allowed to do so. In other words, for some reason, you never need to make any changes to the design of the class, or for security reasons, you don't want it to have subclasses.

Because the final class prohibits inheritance, all methods in the final class are implicitly specified as final because they cannot be overwritten. You can add a final modifier to a method in the final class, but this does not add any meaning.

The finally keyword:

For some code, you might want to be able to execute regardless of whether the exception in the try block is thrown. This usually applies to situations outside of memory reclamation.

1. Finally is important for languages that do not have a garbage collection mechanism and the automatic invocation mechanism of destructors. It allows the programmer to guarantee that memory will always be released regardless of what happens in the try block. But Java has a garbage collection mechanism, so memory deallocation is no longer a problem. Also, Java does not have destructors to call.

When you want to restore resources outside of memory to their initial state, a finally clause is used. Resources that need to be cleaned up include open files or network connections, graphics on the screen, or even a switch from the outside world.

2. Use finally in return.

The program in the finally block executes before the return is executed.

Finalize () method:

Java provides Finalize () method, when the garbage collector is ready to release memory, the Finalize () is called first.

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

Understanding Finalize()-a substitute for a 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.

Conclusion

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.

Public class Finalizationdemo { public static void Main (string[] args) {Cake C1 = new Cake (1); Cake C2 = new Cake (2); Cake C3 = new Cake (3 ); C2 = C3 = null ; System.GC (); //Invoke the Java garbage collector }}class Cake extends Object { private int ID; Public Cake (int ID) { this. id = ID; System.out.println ("Cake Object" + ID + "is created"); } protected void Finalize () throws java.lang.Throwable { super . Finalize (); System.out.println ("Cake Object" + ID + "is disposed"
);    }}

Results:

Cake Object 1is Createdcake Object 2is Createdcake Object 3is Createdcake Object 3is disposedcake object 2is disposed

[java]final keyword, finally keyword, and finalize () method

Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.