JAVA:SYSTEM.GC () and Finalize usage scenarios

Source: Internet
Author: User

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

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.