The garbage collector (GC) only knows how to release the memory allocated by the New keyword, so it does not know how to dispose of the object's "special" Memory . To solve this problem, Java provides a method calledFinalize () , which defines it for our class.
Ideally, the Finalize () method works like this: Once CG is ready to release the memory space occupied by the object, it calls the Finalize () method first, and the memory of the object is actually reclaimed only during the next garbage collection process.
GC! = destructor, the garbage collector is not equal to the destruction device.
To force the finishing touches ( performing some sort of cleanup work other than freeing the object storage ), you can call System.GC () before calling System.runfinalization (). This clears all objects that you have not used so far. A slightly odd thing to do is to call GC () before calling Runfinalization (), which seems to contradict the Sun's documentation stating that it first runs the closure module and frees up storage space. However, if you call Runfinalization () first and then the GC (), the closing module will not execute at all.
For all objects, Java1.1 sometimes defaults to skipping the finishing touches because it thinks the overhead of doing so is too high . Regardless of the method used to enforce garbage collection, you may notice a longer delay than when there is no additional finishing work.
One of the most useful parts of finalize () is to observe the garbage collection process
Public classGarbage { Public Static voidMain (string[] args) { while(!chair.f) {NewChair (); NewString ("To take up space"); } System.out.println ("After all chairs has been created:\n" + "total created =" + chair.created + ", total finalized =" +chair.finalized); System.out.println ("GC ():"); System.GC (); System.out.println ("Runfinalization ():"); System.runfinalization (); System.out.println ("Bye!"); }} Public classChair {Static BooleanGcrun =false; Static Booleanf =false; Static intCreated = 0; Static intfinalized = 0; inti; PublicChair () {i= ++created; if(created = = 47) {System.out.println ("Created 47"); } } protected voidFinalize () {if(!Gcrun) {Gcrun=true; System.out.println ("Beginning to finalize after chairs been created."); System.out.println ("I=" +i); System.out.println ("Created=" +created); } if(i = = 47) {System.out.println ("Finalize chair #47, setting flag to stop chair creation."); F=true; } finalized++; if(Finalized >=created) {System.out.println ("All finalized."); } }}
Java cleanup: Finishing and garbage collection