Centos – Linux top not tallying with java used memory

centosjavatop

We have a java application where towards the last part of the codes we wrote these lines

Runtime runtime = Runtime.getRuntime();
long memory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("\n\nUsed memory is bytes: " + memory);

What we notice is that over time the top shows increase in the memory(%) column for the application but the java memory(from runtime variables) values shows fluctuation up and down? So which should we follow to decide on exact memory usage? My intention is to identify if there is any memory leakage in my application?

Best Answer

When JVM starts, It takes some memory from the operating system. This is the amount of memory you see in tools like ps and top.

Then your applications start using this memory : That's the memory you see with your code and tools like jstat.

So if you want to debug memory leak inside your app, you don't want to use top or ps.