Calculating Used Memory of a JVM
<p>I want to calculate the used memory of a JVM heap. I did the following in a sample application.</p>

<ol>
<li><p>Set JVM heap size as Xms=200mb and Xmx=200mb. </p></li>
<li><p>Did the calculation as follows using Java Runtime APIs. It gave me following output for sample program.</p>

<p>Runtime total memory : 192413696</p>

<p>Runtime max memory : 192413696</p>

<p>Runtime free memory : 39734096</p>

<p>Runtime available memory = (max - total + free) = 39734096</p>

<p>Percentage of used memory = 100*(max-available)/max = 100*(192413696- 
   39734096)/192413696 = 79.35%</p></li>
<li><p>Did another calculation via JMX : java.lang:type=Memory (Using MBean)</p>

<pre><code>It gave me following output for the same program.

Used memory : 127737896

Max memory : 201850880

Percentage of used memory = 100*(used/max) = 100* (127737896/201850880)= 
63.28%
</code></pre></li>
</ol>

<p>Could you please help me with the following ?</p>

<ol>
<li><p>What is the reason for the difference between using JMX and Java Run time APIs ?</p></li>
<li><p>If I want to know the memory occupied in my JVM heap which is the right approach (point 2 or point 3). My intention is to raise alerts before an out of memory occurs for my JVM.</p></li>
</ol>

<p>I have another observation as well. When I use CMS algorithm (with -Xms and -Xms set to 32GB and Occupancy fraction set to 70%) I could see the difference between the free memory calculated using MBeans and java runtime freeMemory(). When I was using G1 I could not find these difference (the Mbeans and run time API gave same value).</p>