» » How to call garbage collector explicitly?

  • When there are no more references to an object, the object is finalized and when the Garbage Collections starts these finalized objects gets collected this will done automatically by jvm.
  • But if we want to call  Garbage collection explicitly, There are methods
    1.System.gc();
    2.Runtime.gc(); 
How to prove?
  • The java.lang.Runtime.freeMemory() method returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by freeMemory
Class GcDemo{

public static void main(String args[]){
System.out.println(Runtime.getRuntime().freeMemory());

    for (int i=0;i<= 100000;i++) {
    Double d = new Double(225);
    }
    System.out.println(Runtime.getRuntime().freeMemory());
    System.gc();
    System.out.println(Runtime.getRuntime().freeMemory());
}

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

2 comments for How to call garbage collector explicitly?

  1. its really appreciable work from you guys...it will work in clearing the java interview if v follow your tips and way of explanation.

    keep helping others. thank you

    ReplyDelete
  2. Helpful for cracking java core interviews!! . Keep posting! Nice contents!

    ReplyDelete

Select Menu