Finalize the role of the implementation of a method before the garbage collection, this method can not put the recycling of resources, such as closing the stream, etc., because this method is not necessarily called
This method is only called when garbage collection is used
The following example is a usage scenario for finalize
Package Day20150814;public class Finalize {public static void main (string[] args) {Check check1 = new Check (), Check2 = new Check (); check1.dochecked ();//check1 execution Method System.out.println ("Check1:" +check1); System.out.println ("Check2:" +check2); check1=null;//loses the citation check2=null; System.GC ();//Forced Gc//runtime.getruntime (). GC ();}} Class Check{private Boolean checked; Check () {checked=false;} public void dochecked () {checked = true;} @Overrideprotected void Finalize () throws Throwable {//TODO auto-generated method StubSystem.out.println ("Finalize"); if (!checked) {System.out.println (this+ "dochecked not executed ~");} Else{system.out.println (this+ "dochecked executed ~ ~");} Super.finalize ();}}
Execution Result:
Check1:[email protected]
Check2:[email protected]
[GC 323k->320k (19648K), 0.0032962 secs]
[Full GC 320k->201k (19648K), 0.0098180 secs]
Finalize
[email protected] did not execute ~
Finalize
[email protected] executed ~ ~
Summary:
Finalize can be placed in a class as a validation of the object's finalization criteria, and some conditions are judged when the resource is recycled.
In addition, System.GC () will not recycle all the resources, only the resources that have lost the reference, so add check1=null code
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
JAVA:SYSTEM.GC () and Finalize usage scenarios