Java Finalize and Garbage Collection

Source: Internet
Author: User

Java garbage collection mechanism:

Java garbage collection is not equivalent to a destructor in C + +. In Java, the space occupied by an object is freed only when the program is on the verge of storage space. So, in a Java program, we usually only consider creating objects, and never care about object cleanup. This strategy is appropriate because the garbage collection itself has a cost, and if you don't use it, you don't have to pay for that part of the cost.

Under what circumstances do we need finalize () :

With garbage collection, we generally do not need to care about object space release, but in some special memory areas, we need to manually clear.

A special memory area is when allocating memory, if an object is processing a non-Java resource, for example, calling the malloc () function like C, allocating storage space, and unless the free () function is called, the storage space will not be freed, resulting in a memory leak. Of course, free () is a function in C and C + +, so you need to call it in Finalize () with a local method, such as a file handle or a window character font, and you want to make sure that the resources are freed before an object is revoked.

Because once the garbage collector is ready to release the storage space occupied by the object, its finalize () method is called first, and the memory occupied by the object is actually reclaimed when the next garbage collection action occurs. So we'll write the manual cleanup method in the Finalize () function.

protected void Finalize () {//  finalization codehere}

Where the keyword protected is to prevent code that is defined outside the class from accessing the Finalize () identifier.

There are three scenarios in which finalize () is called :

1. All objects are automatically called when garbage collection, such as when running System.GC ().

2. When the program exits, a finalize method is called for each object.

3. Explicitly call the Finalize method

Java Finalize and Garbage Collection

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.