title: How to track any object creation in Java since freeMemory() only reports long-lived objects?
body: <p>Whenever a new object is created by my JVM I want to print something in the log. I was trying to detect that using Runtime.getRuntime().freeMemory() but unfortunately it does NOT take into account any short-lived object until it is promoted to the heap (<a href="https://stackoverflow.com/questions/9809920/how-to-track-any-object-instantiation-on-my-jvm-with-runtime-freememory-and-gc">check here for more details</a>).</p>
  
  <p>So does anyone know how to detect/track whenever an object is instantiated/created by my JVM? To make it easier, how do we complete the code below:</p>
  
  <p><strong>Feel free to use MemoryPoolMXBean and JMX:</strong></p>
  
  <pre><code>public class MemoryUtils {
  
      private static Set&lt;String&gt; set = new HashSet&lt;String&gt;();
  
      public static void main(String[] args) {
  
          // START
  
          // now create a bunch of objects and save them in the set
          for (int i = 0; i &lt; 100; i++) {
              set.add(new String("foo" + i));
          }
  
          // FINISH
  
          // FIXME: Do something here to detect that a bunch of objects were created!
  
      }
  }
  </code></pre>
  
  <p><strong>Edit:</strong> Trying solution proposed by Vladimir below:</p>
  
  <p>It works, but with a weird side-effect:</p>
  
  <pre><code>long t = totalThreadMemoryAllocated();
  
  // did nothing
  
  t = totalThreadMemoryAllocated() - t;
  
  System.out.println(t); // ==&gt; 48 !!!???
  
  public static long totalThreadMemoryAllocated() {
      com.sun.management.ThreadMXBean tBean = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
      return tBean.getThreadAllocatedBytes(Thread.currentThread().getId());
  }
  </code></pre>
  
  <p>But it DOES account for any object creation so I guess I could use this if I subtract the magic number 48 from it.</p>