Here is a Java Program to Demonstrate totalMemory(), freeMemory() and gc().
Output of Above Java Program
Total memory is: 16121856
Initial free memory: 15837912
Free memory after garbage collection: 16123344
Free memory after allocation: 16031528
Memory used by allocation: 91816
Free memory after collecting discarded Integers: 16123344
class MemoryDemo { public static void main(String args[]) { Runtime r = Runtime.getRuntime(); long mem1, mem2; Integer someints[] = new Integer[1000]; System.out.println("Total memory is: " + r.totalMemory()); mem1 = r.freeMemory(); System.out.println("Initial free memory: " + mem1); r.gc(); mem1 = r.freeMemory(); System.out.println("Free memory after garbage collection: " + mem1); for(int i=0; i<1000; i++) someints[i] = new Integer(i); // allocate integers mem2 = r.freeMemory(); System.out.println("Free memory after allocation: " + mem2); System.out.println("Memory used by allocation: " + (mem1-mem2)); // discard Integers for(int i=0; i<1000; i++) someints[i] = null; r.gc(); // request garbage collection mem2 = r.freeMemory(); System.out.println("Free memory after collecting" + " discarded Integers: " + mem2); } }
Output of Above Java Program
Total memory is: 16121856
Initial free memory: 15837912
Free memory after garbage collection: 16123344
Free memory after allocation: 16031528
Memory used by allocation: 91816
Free memory after collecting discarded Integers: 16123344