Monday, August 5, 2013

Requesting Garbage Collector(GC) to free up the memory

This would be useful, if you are working on memory critical applications and your application/process want to call GC explicitly to acquire some free memory based on the need.

public class MemoryTest {

public static void callGC() {
long before = Runtime.getRuntime().freeMemory();

/* Let the finilizer finish its work and remove objects from its queue */
System.gc(); /* asyncronous garbage collector might already run */
System.gc(); /* to make sure it does a full gc call it twice */
System.runFinalization(); //Runs the finalization methods of any objects pending finalization. 

try {
} catch (InterruptedException e) {
// do nothing

long after = Runtime.getRuntime().freeMemory();
System.out.print("Total Memory:: ");
System.out.print("Free Memory Before GC:: ");
System.out.print("Free Memory After GC:: ");
System.out.print("Memory gained after GC:: ");
System.out.println(String.valueOf(after - before));

public static void main(String[] args) {

No comments:

Post a Comment