Author Profile Altaf Shaikh
Altaf Shaikh

BE Engg | Python Dev | Content Writer | Founder of TeachMeBro | Blockchain Dev | Django

Garbage Collection In JVM

October 15th 2020   17

Garbage Collection In JVM
Garbage Collection In JVM

Garbage collection:

  • In Java, the programmer needs not to care for all those objects which are no longer in use. Garbage collector destroys these objects.
  • Main objective of Garbage Collector is to free heap memory by destroying unreachable objects.
  • Unreachable objects : An object is said to be unreachable iff it doesn’t contain any reference to it. Also note that objects which are part of island of isolation are also unreachable.

Ways for requesting JVM to run Garbage Collector

  • Once we made an object eligible for garbage collection, it may not be destroyed immediately by the garbage collector. Whenever JVM runs the Garbage Collector program, then only the 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 :
    • Using System.gc() method : System class contains static method gc() for requesting JVM to run Garbage Collector.
    • 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.


java garbage collection example

By explicitly assigning the ‘null’ value to the obj. Example: obj=null in the above diagram will also destroy the object and obj gets ready for the Garbage Collection.