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 (check here for more details).
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:
Feel free to use MemoryPoolMXBean and JMX:
public class MemoryUtils {
private static Set<String> set = new HashSet<String>();
public static void main(String[] args) {
// START
// now create a bunch of objects and save them in the set
for (int i = 0; i < 100; i++) {
set.add(new String("foo" + i));
}
// FINISH
// FIXME: Do something here to detect that a bunch of objects were created!
}
}
Edit: Trying solution proposed by Vladimir below:
It works, but with a weird side-effect:
long t = totalThreadMemoryAllocated();
// did nothing
t = totalThreadMemoryAllocated() - t;
System.out.println(t); // ==> 48 !!!???
public static long totalThreadMemoryAllocated() {
com.sun.management.ThreadMXBean tBean = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
return tBean.getThreadAllocatedBytes(Thread.currentThread().getId());
}
But it DOES account for any object creation so I guess I could use this if I subtract the magic number 48 from it.