Clear java-4.5 objects from the ground up (finalize ())

Source: Internet
Author: User

Clear java-4.5 objects from the ground up (finalize ())

In this section, we will briefly discuss how to clean up objects.

Note: The Destructor is provided in c ++ to clear objects. However, in java, objects are recycled by the garbage collector. The recycle object is not necessarily destructed, because it is recycled only when the memory of the recycler exceeds a certain limit. Therefore, it is possible that the object is only recycled, however, only when the program is closed will the structure be destructed, because the recycler has not reached the limit.

In JAVA, finalize () is generally used to indicate object recycling.

 

package com.ray.ch01;public class Test {public static void main(String[] args) {try {new Test().finalize();} catch (Throwable e) {e.printStackTrace();}}}

When the object calls finalize (), it will be recycled in the next garbage collection.

 

Note that the collection of objects is only related to memory.

However, we need to use garbage collection with caution in the code, because it is unpredictable and dangerous.

We usually use the finalize () function as a gc condition detection.

 

package com.ray.ch01;public class Test {public static void main(String[] args) {Book book = new Book(true);book.checkIn();new Book(true);System.gc();}}class Book {private boolean checkOut = false;public Book(boolean checkOut) {this.checkOut = checkOut;}public void checkIn() {this.checkOut = false;}@Overrideprotected void finalize() throws Throwable {if (checkOut) {System.out.println(error);//super.finalize();}}}

Output:

 

Error

The above code can be correctly displayed only under debug conditions.

 

Summary: This chapter mainly discusses some considerations for object cleanup. But in fact, object cleanup is a very big topic. We can only expand it more deeply.

 

 

 

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.