I have been taking few different heap snapshots. What I see is that the memory usage is not the same as reported by this codes. So how to know the exact memory is being used by my java application. I also see my leak report from MAT reports a lot of finalize stuff is that any thing danger there.
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
//runtime.gc();
// Calculate the used memory
long memory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("\n\nUsed memory is bytes: " + memory);
//Print the jvm heap size.
long heapSize = runtime.totalMemory();
System.out.println("\n\nHeap Size = " + heapSize);
int mb = 1024*1024;
System.out.println("##### Heap utilization statistics [MB] #####");
//Print used memory
System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);
//Print free memory
System.out.println("Free Memory:" + runtime.freeMemory() / mb);
//Print total available memory
System.out.println("Total Memory:" + runtime.totalMemory() / mb);
//Print Maximum available memory
System.out.println("Max Memory:" + runtime.maxMemory() / mb);