Demonstrate totalMemory()
, freeMemory()
and gc()
.
public class Main { public static void main(String args[]) { Runtime r = Runtime.getRuntime(); long m1, m2;//from w ww . j a va 2s .c o m Integer someints[] = new Integer[1000]; System.out.println("Total memory is: " + r.totalMemory()); m1 = r.freeMemory(); System.out.println("Initial free memory: " + m1); r.gc(); m1 = r.freeMemory(); System.out.println("Free memory after garbage collection: " + m1); for (int i = 0; i < 1000; i++) { someints[i] = new Integer(i); // allocate integers } m2 = r.freeMemory(); System.out.println("Free memory after allocation: " + m2); System.out.println("Memory used by allocation: " + (m1 - m2)); // discard Integers for (int i = 0; i < 1000; i++) { someints[i] = null; } r.gc(); // request garbage collection m2 = r.freeMemory(); System.out.println("Free memory: " + m2); } }