Java Garbage Collector

Source: Internet
Author: User

The garbage collector only knows how to release memory allocated by new. Once the garbage collector is ready to recycle new objects, it will first call the finalize () method, which can clean up the garbage collection.

This means that if you have to execute some actions before you need an object, you have to perform the finalize () method on your own ). Generally, you cannot expect finalize (). You must create other "Cleanup" methods and call them explicitly. Finalize (): verifies the object "Terminator condition.

Class finalizetest ...{
Public static void main (string [] ARGs )...{
Auto auto = new auto (); // when an object is not referenced, it becomes garbage. The new object in this sentence is not garbage.
Auto = NULL; // The new object is junk.
New auto ();
New auto ();
System. GC ();
}
}

Class auto ...{
Public void finalize ()...{
System. Out. println ("Auto is going ");
}
}

PS: If the finalize () method is placed in the auto class, the new auto () object will be called when it is recycled. If the finalize () method is placed in the finalizetest class, new auto () objects will not be called when they are recycled, and new finalizetest () objects will be called only when they are recycled.

Running result:

Auto is going
Auto is going
Auto is going

Another application instance

 

Class book ...{
Public Boolean checkedout = false;
Public book (Boolean checkout )...{
Checkedout = checkout;
}
Public void checkin ()...{
Checkedout = false; // status conversion & normalize the checkedout variable to false
}
Public void finalize ()...{
If (checkedout)
System. Out. println ("This book has not executed checkin ");
}
Public static void main (string [] ARGs )...{
Book thinkinginjava = New Book (true );
Thinkinginjava. checkin ();

Book Datastructure = New Book (true );
Datastructure = NULL;
System. GC ();
}
}

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.