First, Finalize and GC
When the GC first performs a accessibility analysis, it will be unreachable and the object's class overrides the Finalize method and the Finalize method has not been executed again to append to the F-queue. The JVM then automatically opens a low-priority daemon thread finalizer executes the Finalize method of the elements in F-queue. You can then re-associate the unreachable object with the reference chain through the Finalize method, then you can escape the recycled list when the GC is in for the second time for accessibility analysis.
classfinalizeescapegc{ Public StaticFINALIZEESCAPEGC Save_hook =NULL; Public voidisAlive () {System. out. println ("Yes, I am still alive;"); } @overrideprotected voidFinalize () throws throwable{super.finalize (); System. out. println ("Finalize Method executed!"); Finalizeescapegc.save_hook= This; } Public Static voidMain (string[] args) throws throwable{Save_hook=NewFINALIZEESCAPEGC (); Save_hook=NULL; System.GC (); Thread.Sleep ( -); if(Save_hook = =NULL) save_hook.isalive (); ElseSystem. out. println ("No, I am dead:("); Save_hook=NULL; System.GC (); Thread.Sleep ( -); if(Save_hook = =NULL) save_hook.isalive (); ElseSystem. out. println ("No, I am dead:("); }}
Successfully escaped the recovery list for the first time through the Finalize method, but the second time because the Finalize method has been called before, so the Finalize method is not executed, so it is destined to be recycled.
Note: The finalizer thread executes the Finalize method for each object when it is non-blocking, so it does not guarantee that the Finalize method executes when the GC is marked for a second time.
Ii. releasing resources in the Finalize method?
When you talk about the Finalize method, you'll think of destructors, and you'll want to use them like destructors, and then all of the resource release touches are put in the Finalize method. In fact, this is just to make it easier for C/+ + programmers to turn to the Java camp compromise, it is best to forget this method, the release of resources through try-catch-finally more effective.
Respect the original, reprint please indicate from: http://www.cnblogs.com/fsjohnhuang/p/4269086.html ^_^ Fat Boy John
Java Magic Hall: Finalize function