Java-based garbage collection

Source: Internet
Author: User

1/** 2 * when no reference is available, the lifecycle ends and becomes garbage. 3 * The finalize () method is automatically called for all objects before they are recycled. 4 *************************************** * ************ 5 * an object will not be recycled immediately after it becomes garbage, 6 * The JVM will detect the accumulation of garbage in the memory to a certain extent before it will be recycled. 7 * if we don't want to wait until then, 8 * can use System. gc () method to notify the virtual machine to recycle garbage. 9 * after this method is called, The JVM will start a new thread to process the garbage, which takes some time. 10 */11 public class GcDemo {12 13 public static void main (String [] args) throws Exception {14 15 for (int I = 0; I <1000; I ++) {16 new Person (); // after an object is created, it is not used as garbage 17} 18 System. out. println ("before recycling:" + Person. count); 19 System. gc (); // notify the virtual machine to recycle garbage 20/* 21 * call System. after gc (), the JVM starts a new thread to process garbage. It takes a certain amount of time for the JVM to sleep for a few seconds, check the effect of garbage collection. 22 * It takes up to 23 */24 threads for garbage collection. sleep (1000); 25 System. out. println ("after recycling:" + Person. count); 26} 27 28} 29 30 class Person {31 // define a count to count, view 32 public static int count before and after collection; 33 34 public Person () {35 count ++; // each time an object is created, count Plus 36} 37 // all objects automatically call the finalize () method 38 public void finalize () before being recycled () {39 count --; // clear a garbage and subtract a 40} 41}

 

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.