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