每当我的JVM创建一个新对象时,我想在日志中打印一些东西。我试图使用Runtime.getRuntime()。freeMemory()来检测,但不幸的是它没有考虑到任何短暂的对象,直到它被提升到堆(check here for more details)。
那么有没有人知道如何检测/跟踪每当一个对象由我的JVM实例化/创建?为了更容易,我们如何完成下面的代码:
随意使用MemoryPoolMXBean和JMX:
public class MemoryUtils {
private static Set set = new HashSet();
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!
}
}编辑:尝试下面的弗拉基米尔提出的解决方案:
它有效,但有一个奇怪的副作用:
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());
}但它确实解释了任何对象的创建,所以我想我可以使用这个,如果我从它减去48的魔术数。