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 {
Thread.sleep(100);
} catch (InterruptedException e) {
// do nothing
}
long after = Runtime.getRuntime().freeMemory();
System.out.print("Total Memory:: ");
System.out.println(String.valueOf(Runtime.getRuntime().totalMemory()));
System.out.print("Free Memory Before GC:: ");
System.out.println(String.valueOf(before));
System.out.print("Free Memory After GC:: ");
System.out.println(String.valueOf(after));
System.out.print("Memory gained after GC:: ");
System.out.println(String.valueOf(after - before));
}
public static void main(String[] args) {
callGC();
}
}
No comments:
Post a Comment