Garbage Collector in Java

Java is capable of automatically releasing the unreferenced memory. This is achieved when a object is unused. To make a object unused make the reference variable pointing to that object as null pointer.
Lets see an Example below,

public void TestMethod()
{
String s = new String("Welcome to CodeParent");
System.out.println(s);
s = null;
}

Other options in java you can use System.gc() and Runtime.gc() methods, if you call these methods explicitly, the JVM makes efforts towards recycling the unused objects, but there is no guarantee that when the objects are garbage collected.

Happy coding during coronavirus time and try for freelancing in your free time.

Points to Remember:

  • It’s a good idea to explicitly assign null into a variable (to guarantee garbage collection) when you have finished with it.
  • Only objects are garbage collected not the reference.
  • Users can also use finalize() method by overriding it and can perform the necessary objects to be clean up. Because java deletes objects using a garbage collector at inconsistent intervals.

Leave a Reply