Destruction method analysis of objects in Java

  • 2020-04-01 03:48:49
  • OfStack

This article has analyzed the destruction method of object in Java in detail. Share with you for your reference. Specific analysis is as follows:

Basic data type variables and object name reference variables in Java are local variables if defined in a method. But the object itself is not necessarily a local lifecycle. If there are other reference variables to the object outside the function, the life cycle of the object extends to the block where the other reference variables are located.

If the value or return value is passed from the parameter reference of the called function to the object type variable where the main calling function is located, the object still exists (but the life cycle of the reference variable of the object of the called function is over, so the reference variable is a local variable), and the object breaks through the local life of the local variable.

Java object destruction

The garbage collector in Java automatically scans the dynamic memory of Java objects periodically and marks all referenced objects. After the object runs (no referenced variables are associated with the object), the garbage collector clears its mark and collects all unmarked objects as garbage, freeing up the memory space occupied by garbage objects.

Objects become garbage objects after they are run or at the end of their life cycle, but that does not mean they are immediately collected, only when the garbage collector is free or out of memory.

Each object in Java has a finalize() method:


protected void finalize()throws Throwable{}

The garbage collector automatically calls the finalize() method of the object when it is collected to free up system resources.

Finalize () function prototype:

protected void finalize()
Called by the garbage collector on an object when garbage
collection determines that there are no more references to
the object.
I hope this article has been helpful to your Java programming.


Related articles: