Differences between final, finally, and finalize in java

Source: Internet
Author: User
Tags abstract constructor finally block garbage collection modifier stmt

Final-modifier (keyword) if a class is declared as final, it means that it cannot generate a new subclass and cannot be inherited as a parent class. Therefore, a class cannot be declared both abstract and final. Declare variables or methods as final to ensure that they are not changed during use. Variables declared as final must be declared with an initial value, which can only be read and cannot be modified in future references. Methods declared as final can only be used and cannot be overloaded.


Final variable definition: once initialized, variables cannot point to other objects. The address to which the object belongs cannot be modified, but the object to which the address belongs can be modified.

Let's first talk about final variable initialization:

Many articles have said this: the initialization can be in two places: one is its definition, and the other is in the constructor. Either of them can be selected.
Nonsense!
Final variables can be initialized at any place where they can be initialized, but can only be initialized once. Once initialized, they cannot be assigned again.
Value (re-pointing to other objects), must be explicitly initialized as a member variable, while as a temporary variable, you can only define and do not initialize (of course, cannot reference)
Even as a member variable in a class, it can also be initialized in the initialization block, so "the initialization can be in two places. One is its definition,
Second, in the constructor, either of the two can be "incorrect.


As a member variable, the final field can be designed as a non-variable class, which is a required condition but not a sufficient condition. At least it can ensure that the field is not
It will be changed in the form of setXXX (), but it cannot be ensured that the field itself is not modified (unless the field itself is also a constant class );

For final variables of method parameters:
If the variables of method parameters are defined as final, more than 90% of the articles say, "When you do not need to change the object variables used as parameters in methods, make it clear
Using final statements will prevent you from accidentally modifying the variables outside the calling method. "
Nonsense!

I don't know whether this modification refers to re-assigning the value or modifying the object itself, but in either case, the above statement is wrong.
If the value is re-assigned, then:

The code is as follows: Copy code

Public static void test (int [] x ){
X = new int [] {1, 2, 3 };
}

Int [] out = new int [] {4, 5, 6 };
Test (out );
System. out. println (out [0]);
System. out. println (out [1]);
System. out. println (out [2]);

Call test (out); in any case, it will not affect the out variable. It doesn't make sense if you add final. final will only force the method
Declare one more variable name, that is, change x = new int [] {1, 2, 3}; to int y = new int [] {1, 2, 3 }; nothing else actually makes sense.
If it is to modify the object itself:

The code is as follows: Copy code
Public static void test (final int [] x ){
X [0] = 100;
}
Int [] out = new int [] {4, 5, 6 };
Test (out );
System. out. println (out [0]);

Can't you modify the final modification? Therefore, the final in the method parameters is used to avoid affecting the variables outside the called method.

So why should we add final to the parameter? In fact, adding final to method parameters is the same as adding final to Method variables, that is,
Callback method passed to internal class:

The code is as follows: Copy code

Abstract class ABSClass {
Public abstract void m ();
}

Now, if I want to implement an anonymous call to ABSClass in a method, we should:

The code is as follows: Copy code

Public static void test (String s ){
// Or String s = "";
ABSClass c = new ABSClass (){
Public void m (){
Int x = s. hashCode ();

System. out. println (x );

   }
};
// Other code.
}

Note that the callback method is generally called in other threads.
 

The code is as follows: Copy code

ABSClass c = new ABSClass (){
Public void m (){
Int x = s. hashCode ();

System. out. println (x );

   }
};

The subsequent direct call of c. m (); should be meaningless. But this is not important. The important thing is that as long as it may be called in other threads, we must
Saves the reference handle for s.

Let's take a look at the working principle of GC. Every process in JVM has multiple roots, each static variable, method parameter, and local variable. Of course, this is a guiding type.
The basic type cannot be the root, but the root is actually a storage address.

When GC is working, it first traverses the referenced objects from the root and marks them, so that the recursion is to the final end. After all the roots are traversed, the objects not marked are not described.
Objects that can be recycled (some objects have the finalized method, although not referenced, but the JVM has a dedicated queue to reference it)
They are not removed from the queue until the finalized method is executed and can be recycled. This is irrelevant to the topic, including
The division of generation will be explained later). This looks good.

However, in the callback method of the internal class, s is neither a static variable nor a temporary variable in the method, nor a method parameter. It cannot be used as the root of the internal class.
There is no variable to reference it. In the internal class external method, if the external variable points to another object, the object will lose the reference,
It may be recycled. Because most of the internal class callback methods are executed in other threads, they may still be accessed after being recycled. What is the result?

Using the final modifier will not only keep the object unchanged, but also the compiler will continue to maintain the lifecycle of this object in the callback method. Therefore, this is final.
The fundamental significance of variables and final parameters.

 

Finally-the finally block is provided for troubleshooting. If an exception is thrown, the matched catch clause is executed, and the control enters the finally block (if any ).

We rummaged through the ancient secret books and finally lost the book "call, wipe!" at the top of the Cave in Beijing. An absolute clean method is found, that is ------------

Just a moment!

The procedure is as follows:

 

Code

The code is as follows: Copy code
Void f (){
Final Connection conn = ...;
Try {
Final Statement stmt = ...;
Try {
Final ResultSet rset = ...;
Try {
...
      }   
Finally {rset. close ();}
    }   
Finally {stmt. close ();}
  }   
Finally {conn. close ();}


The trick is that every time a resource needs to be cleared is created, a try-finally command is used to ensure that it can be cleared.

At any time, you leave the bathroom quietly.

. A lot of Saints told me that they were very unsightly (look at the nested try block), against the ancient ceremony. We disagree!

By the way, do you say Kong Luer er Gu or Shan Ding Dong Ren Gu ??
What is the elegance of your ass "?

In addition, you can also pull a curtain if you want to lose your face. Don't let people see it when you clean it. For example:

 

Code

The code is as follows: Copy code

Interface ResultListener {
Void call (ResultSet rset );
}   
Class SqlReader {
Void read (ResultListener l ){
Final Connection conn = ...;
Try {
Final Statement stmt = ...;
Try {
Final ResultSet rset = ...;
Try {
L. call (rset );
        }   
Finally {rset. close ();}
      }   
Finally {stmt. close ();}
    }   
Finally {conn. close ();}
  }   

 


Finalize-method name.

Finalize is equivalent to a destructor. It is the first method to be called when the garbage collector recycles an object. However, because Java's garbage collection mechanism can automatically do these tasks for us, we generally do not need to manually release them.

 

Some operations are required to cancel an object. For example, if an object is processing non-Java resources, such as a file handle or a window font, make sure that these resources are released before an object is revoked. To handle such a situation, Java provides a mechanism called finalization. You can use this mechanism to define some special operations that are executed when an object is to be released by the garbage collection program.
To add finalizer to a class, you only need to define the finalize () method. This method is called when Java recycles an object of this class. In the finalize () method, you must specify the operations that must be performed before an object is revoked. Garbage collection runs cyclically, and check that the object is no longer referenced by the running state or indirectly referenced by other objects. Before the object is released, the Java runtime system calls the finalize () method of the object.

The general format of The finalize () method is as follows:

The code is as follows: Copy code

Protected void finalize ()
{
// Finalization code here
}

The keyword protected is used to prevent code defined outside of this class from accessing the finalize () identifier. This identifier and other identifier will be explained in chapter 7th.

It is important to understand that finalize () is called before garbage collection. For example, if an object exceeds its scope, finalize () is not called. This means that you cannot know when -- or even whether -- finalize () is called. Therefore, your program should provide other methods to release the system resources used by the object, rather than relying on finalize () to complete normal operations of the program.

Note: If you are familiar with C ++, you know that C ++ allows you to define a destructor for a class, which is called before the object is out of scope. Java does not support this idea and does not provide undo functions. The finalize () method is only similar to the function of revoking a function. When you have rich experience with Java, you will see that Java uses the garbage collection subsystem and there is almost no need to use the undo function.

 


Finalize should work like this: once the garbage collector is ready to release the storage space occupied by the object, it first calls finalize (), and only in the next garbage collection process, will actually recycle the object memory. therefore, if finalize () is used, important cleanup or cleanup operations can be performed during garbage collection.

When will finalize () be called?
There are three cases
1. All objects are automatically called when they are Garbage Collection, such as when System. gc () is run.
2. The finalize method is called once for each object when the program exits.
3. Explicitly call the finalize method

In addition, under normal circumstances, when an object is collected as useless information by the system, finalize () will be automatically called, but the jvm does not guarantee that finalize () will be called, that is, the call to finalize () is uncertain, which is why sun does not advocate the use of finalize ().

Some operations are required to cancel an object. For example, if an object is processing non-Java resources, such as a file handle or a window font, make sure that these resources are released before an object is revoked. To handle such a situation, Java provides a mechanism called finalization. You can use this mechanism to define some special operations that are executed when an object is to be released by the garbage collection program.

To add finalizer to a class, you only need to define the finalize () method. This method is called when Java recycles an object of this class. In the finalize () method, you must specify the operations that must be performed before an object is revoked. Garbage collection runs cyclically, and check that the object is no longer referenced by the running state or indirectly referenced by other objects. Before the object is released, the Java runtime system calls the finalize () method of the object.

The general format of The finalize () method is as follows:

The code is as follows: Copy code

Protected void finalize ()
{
// Finalization code here
}

The keyword protected is used to prevent code defined outside of this class from accessing the finalize () identifier. This identifier and other identifier will be explained in chapter 7th.

It is important to understand that finalize () is called before garbage collection. For example, if an object exceeds its scope, finalize () is not called. This means that you cannot know when -- or even whether -- finalize () is called. Therefore, your program should provide other methods to release the system resources used by the object, rather than relying on finalize () to complete normal operations of the program.

Java technology allows you to use the finalize () method to clear objects from the memory before the garbage collector clears them. When the garbage collector determines that there is no more reference to this object, the object's garbage collector calls this method. The finalize () method is called before the garbage collector deletes an object.

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.