Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

import java.util.Date; public class CheckGC { public static void main(String []

ID: 3871387 • Letter: I

Question

import java.util.Date;
public class CheckGC {
public static void main(String [] args) {
Runtime rt = Runtime.getRuntime();
System.out.println("Total JVM memory: "
+ rt.totalMemory());
System.out.println("Before Memory = "
+ rt.freeMemory());
  
Date d = null;
for(int i = 0;i<10000;i++) {
d = new Date();
d = null;
}
System.out.println("After Memory = "
+ rt.freeMemory());
  
rt.gc(); // an alternate to System.gc()
  
System.out.println("After GC Memory = "
+ rt.freeMemory());
  
}
}


Try changing the CheckGC java program by putting lines 13 and 14 inside a loop. You might see that not all memory is released on any given run of the GC

Explanation / Answer

//Checking working of gc call
//CheckGC.java
import java.util.Date;
public class CheckGC {
   public static void main(String [] args) {
       Runtime rt = Runtime.getRuntime();
       System.out.println("Total JVM memory: "
               + rt.totalMemory());
       System.out.println("Before Memory = "
               + rt.freeMemory());

       Date d = null;

       //Note : loop run for 10 times for understanding of free memory
       for(int i = 0;i<10;i++) {
           d = new Date();
           d = null;
           //Line 13:
           //Force garbage collection to release
           //memory that is no longer needed by
           //program for Date object will be released
           rt.gc(); // an alternate to System.gc()
           //Line 14:
           //print the free memory after releasing
           //the occupied memory by data object,d
           System.out.println("After GC Memory = "
                   + rt.freeMemory());
       }
       System.out.println("After Memory = "
               + rt.freeMemory());

   }
}

----------------------------------------------------------------------------

Sample output:

Total JVM memory: 16252928
Before Memory = 15709880
After GC Memory = 15979536
After GC Memory = 15979408
After GC Memory = 15979408
After GC Memory = 15979856
After GC Memory = 15979856
After GC Memory = 15979856
After GC Memory = 15979856
After GC Memory = 15979856
After GC Memory = 15979856
After GC Memory = 15979856
After Memory = 15979856


As you can see,

the starting free memory,15709880 and the final free memory, 15979856.

The difference is 269976 bytes memory is still occupied by the process(or thread).

Not all memory is released by gc calling.

So, gc is not guarantees to release all the memory occupied at all times.

So, the behaviour of jvm is different on different machines.