title: How can I get the memory that my Java program uses via Java's Runtime api?
body: <p>There are similar questions out there, but they seem to avoid answering this specific question.  How can I get the memory that <strong>my Java program</strong> uses via Java's Runtime api?</p>
  <p><strong>The answer <a href="https://stackoverflow.com/questions/3571203/what-is-the-exact-meaning-of-runtime-getruntime-totalmemory-and-freememory">here</a> indicates that I can do something like this:</strong></p>
  <pre><code>System.out.println(&quot;KB: &quot; + (double) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024);
  </code></pre>
  <p>But this always returns the same number, no matter which program I run.  For example, below I have a program where no matter how many numbers I put in the map, the memory usage stays the same.</p>
  <pre><code>package memoryTest;
  
  import java.util.HashMap;
  import java.util.Map;
  
  public class MemoryTest {
  
      static Map&lt;Integer, NewObject&gt; map = new HashMap&lt;Integer, NewObject&gt;();
  
      public static void main(String[] args){
  
          System.out.println(&quot;KB: &quot; + (double) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024);
          fillMemory(25);
  
          System.out.println(&quot;KB: &quot; + (double) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024);
      }
  
      static int j=0;
      public static void fillMemory(int i){
  
          for(int k=0; k&lt; 2000; k++)
              map.put(j++, new NewObject());
  
      }
      
  
      public static class NewObject{
          long i = 0L;
          long j = 0L;
          long k = 0L;
      }
      
  }
  </code></pre>
  <p>via cambecc's main method, output is:</p>
  <pre><code># 3085, Total: 128516096, Free: 127173744, Diff: 671120
  # 173579, Total: 128516096, Free: 110033976, Diff: 671128
  # 335207, Total: 128516096, Free: 92417792, Diff: 637544
  # 672788, Total: 224198656, Free: 159302960, Diff: 1221520
  # 1171480, Total: 224198656, Free: 106939136, Diff: 1221544
  # 1489771, Total: 368377856, Free: 227374816, Diff: 1212984
  # 1998743, Total: 368377856, Free: 182494408, Diff: 1212984
  </code></pre>