Garbage Collection in Java

https://blog.csdn.net/justloveyou\_/article/details/71216049

  • But in Java, the programmer need not to care for all those objects which are no longer in use. Garbage collector destroys these objects.
  • Garbage collector is best example of Daemon thread as it is always running in background.
  • Main objective of Garbage Collector is to free heap memory by destroying
    unreachable objects
    .

  • Unreachable objects :

An object is said to be unreachable if it doesn’t contain any reference to it. Also note that objects which are part of island of isolation are also unreachable.

  • Eligibility for garbage collection : An object is said to be eligible for GC(garbage collection) iff it is unreachable. In above image, after i = null; integer object 4 in heap area is eligible for garbage collection.

https://www.geeksforgeeks.org/garbage-collection-java/

Ways for requesting JVM to run Garbage Collector

Once we made object eligible for garbage collection, it may not destroy immediately by garbage collector. Whenever JVM runs Garbage Collector program, then only object will be destroyed. But when JVM runs Garbage Collector, we can not expect.

  • We can also request JVM to run Garbage Collector. There are two ways to do it
      1. Using System.gc() method: System class contain static method gc() for requesting JVM to run Garbage Collector.
      2. Using Runtime.getRuntime().gc() method: Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector.

Note :

    1. There is no guarantee that any one of above two methods will definitely run Garbage Collector.
    2. The call System.gc() _is effectively equivalent to the call : _Runtime.getRuntime().gc()

Finalization

Just before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object.

finalize() method is present in Object class with following prototype

Note :

The finalize() method called by Garbage Collector not JVM. Although Garbage Collector is one of the module of JVM.

Object class finalize() method has empty implementation, thus it is recommended to override finalize() method to dispose of system resources or to perform other cleanup.

The finalize() method is never invoked more than once for any given object.

If an uncaught exception is thrown by the finalize() method, the exception is ignored and finalization of that object terminates.

results matching ""

    No results matching ""