Three states of objects in Java

Source: Internet
Author: User
Tags finally block

The three states of objects in Java are closely related to garbage collection, so it is necessary to delve into them.

State One : accessible states: From the root node, you can search for this object, that is, you can access the object, and some people call it reachable state.

State two : the Resurrection State: starting at the root node, you cannot access the object at all, that is, all references to the object are freed, and no variables refer to the object.

However, the object is likely to be referenced again in the Finalize () method to resurrect.

State three : unreachable states: All references to an object are freed, and there is no resurrection in the object's Finalize () method, so that the object is not reachable.

For state three I'll explain again that all objects have a finalize () method, and that the method is executed only once, and its execution time is random, usually after we assign a value of NULL to the variable,

Executes, if we add a reference to an object in the Finalize () method, the object is resurrected, but when we assign it again to NULL, the Finalize () method is not executed.

Because the method is known to execute once, the object becomes an untouchable state.

Speaking of the Finalize () method, I say a little more, some books write, you can release some resources in the Finalize () method, in fact, this is not recommended by us, there are two main points:

1, the Finalize () method execution time is uncertain, then this will lead to the resources before the release, and a thread needs to access resources, may produce an exception error. Especially in multithreaded programs.

2, the Finalize () method may occur in the reference leak, unintentionally revive the object, thereby producing memory leaks.

It is recommended to release resources in the finally block of the try-catch-finally structure.

Three states of objects in Java

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.