Think in Java Note Finalize () function

Source: Internet
Author: User

1. Overview of the Java garbage collection mechanism

Java is placed in the heap space with the object generated by the new keyword, and the reference handle is placed in the stack space. An object can have multiple references. Because the garbage collector exists, the object is not scoped, and the reference handle is scoped. So, when the last reference of the object ends, or the last reference of the object points to another object or null, that is, when the object has not been referenced by any reference handle, the object can be used by the Java The garbage collector is recycled. The time to recycle occurs is indeterminate, but you can call the GC () method to notify the JVM to reclaim garbage.

2. Finalize ()Method

It is a protected method of the object class that calls itself before the garbage collector reclaims the objects.

3. Finalize ()the call

When the program exits;

When the call is displayed;

Let's discuss the three most important:

The Java garbage collector will call the finalize () method of this object before it reclaims the object, and once the garbage collector is ready to release the storage space occupied by the object, it first calls Finalize (), and the memory of the object is actually reclaimed only during the next garbage collection process. So if you use Finalize (), you can do some important cleanup or cleaning work during garbage collection. (This section refers to a think in Java). Program verification is as follows

Package Chapter.one; Public classGarbage {@SuppressWarnings ("Deprecation")     Public Static voidMain (string[] args) {if(Args.length = =0) {System.err.println ("Usage: \ n"+"java garbage before\n or:\n"+"Java garbage after"); return; }                //Loops         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); if(args[0].equals ("before") ) {System. out. println ("GC ():");            System.GC (); System. out. println ("runfinalization ():");        System.runfinalization (); } System. out. println ("bye!"); if(args[0].equals (" After")) System.runfinalizersonexit (true); }}classchair{StaticBoolean gcrun =false; StaticBoolean f =false; Static intCreated =0;//Static used to count the number of objects created    Static intfinalized =0; inti; Chair () {i= ++created; if(created = = -) System. out. println ("Created"); }            //called before garbage collection@Overrideprotected voidFinalize () {//the GCRUN flag to indicate whether the garbage collector has started running.         if(!Gcrun) {Gcrun=true; System. out. println ("Beginning to finalize after"+created +"chairs have been created"); }        //when F equals true, the main function should stop the creation of the object.        if(i = = -) {System. out. println ("finalizing Chair #47,"+"Setting flag to stop Chair creation"); F=true; } finalized++; if(Finalized >=created) System. out. println (" All"+ finalized +"finalized"); }}

Operating effect:

  231850 chairs have been createdfinalizing Chair # 2476964  1403452GC (): Runfinalization (): Bye!

4.Why do you defineFinalize () method

  Sometimes when you undo an object, you need to do something. For example, if an object is working on a non-Java resource, such as a file handle or a window character font (which is supplemented later in the example), you want to make sure that the resources are freed before an object is undone. To deal with this situation, Java provides a mechanism known as the closing (finalization ).

(It is not recommended to use this method because it cannot be guaranteed) Use this mechanism you can define special operations that are executed when an object is about to be released by the garbage collector.
To add the finishing touches to a class (finalizer), you just define the Finalize () method. This method is called when Java recycles an object of the class.

In general, you want to do something before a dry object is recycled, then write the event into the Finalize () function, and it's not a very urgent thing to do.

5. Finalize ()The method is not omnipotent.

For example, when an object consumes a lot of system resources. At this point, you can't let it go and wait for the garbage collector to recycle, because the garbage collection happens ------ look at the JVM 's mood, so your function should provide other methods before the object's reference is cleared 0. Reclaims the resources that the object occupies.

Think in Java Note Finalize () function

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.