Checking Memory Allocation

We can run the following code to estimate Java VM memory usage in run-time: (Original from StackOverFlow Jeremy answer https://stackoverflow.com/questions/74674/how-do-i-check-cpu-and-memory-usage-in-java with a little modification for console)

To estimate the memory usage of a section, we can user 'System.gc()' to clean up the memory beforehand.

Runtime runtime = Runtime.getRuntime();
NumberFormat format = NumberFormat.getInstance();
StringBuilder sb = new StringBuilder();

long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();

sb.append("free memory: " + format.format(freeMemory) + "\n");
sb.append("allocated memory: " + format.format(allocatedMemory) + "\n");
sb.append("estimate memory usage: " + format.format(allocatedMemory - freeMemory) + "\n");
sb.append("max memory: " + format.format(maxMemory) + "\n");
sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory))) + "\n");

System.out.println(sb.toString());

Output (unit in byte), where estimate memory usage is the used memory:

free memory: 456,934,968
allocated memory: 935,329,792
estimate memory usage: 478,394,824
max memory: 3,294,101,504
total free memory: 2,815,706,680