Unlike C ++, Java has its own garbage collection mechanism. At the same time, Java does not have the Destructor concept, and instead provides a Finalize method, so when will the Finalize method be executed?
Some people may think that when setting the reference to null, let's take a look at the following example:
Public class test {<br/> Public static void main (string [] ARGs) {<br/> // todo auto-generated method stub <br/> demo d = new demo (); <br/> system. out. println ("begin to set D to null"); <br/> d = NULL; <br/> system. out. println ("d was set to null "); <br/>}</P> <p> class demo {<br/> @ override <br/> protected void finalize () throws throwable {<br/> // todo auto-generated method stub <br/> system. out. println ("demo finalized"); <br/> super. finalize (); <br/>}< br/>}
Run the code and the result is as follows:
Begin to set D to null <br/> D was set to null
The Finalize method is not executed at all. Let's take a look at the definition of the Finalize method in Java: called by the garbage collector on an object when garbage collection determines that there are no more references to the object. when the garbage collection confirmation does not point to the object reference, the garbage collection is executed. The unique reference D of the demo object created in the code above has been released, and the Finalize method of the demo class does exist. The only reason is that GC is not executed, GC is automatically executed only when the JVM memory is insufficient. For testing, modify the Code as follows:
Public class test {<br/> Public static void main (string [] ARGs) {<br/> // todo auto-generated method stub <br/> demo d = new demo (); <br/> system. out. println ("begin to set D to null"); <br/> d = NULL; <br/> system. out. println ("d was set to null"); <br/> system. out. println ("begin run GC"); <br/> system. GC (); <br/> system. out. println ("GC Runed "); <br/>}</P> <p> class demo {<br/> @ override <br/> protected void finalize () throws throwable {<br/> // todo auto-generated method stub <br/> system. out. println ("demo finalized"); <br/> super. finalize (); <br/>}< br/>}
The running result is as follows:
Begin to set D to null <br/> D was set to null <br/> begin run GC <br/> GC Runed <br/> demo finalized
Therefore, the Finalize method is executed only when the JVM executes GC. Therefore, when writing code, you must note that the code here does not know when to execute it, so try to use it as little as possible.
Next article: Java tip [006]: Can anonymous internal classes inherit other classes?