由于freeMemory()仅报告长期存在的对象,因此如何跟踪Java中的任何对象创建? [英] How to track any object creation in Java since freeMemory() only reports long-lived objects?
问题描述
每当我的JVM创建一个新对象时,我都希望在日志中打印一些内容.我试图使用Runtime.getRuntime().freeMemory()进行检测,但不幸的是,直到将其提升到堆之前,它都没有考虑任何短期对象(
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).
那么,有人知道我的JVM实例化/创建对象时如何检测/跟踪吗?为了简化操作,我们如何完成以下代码:
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:
随意使用MemoryPoolMXBean和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!
}
}
以下是弗拉基米尔(Vladimir)提出的尝试解决方案:
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());
}
但是它确实说明了任何对象的创建,所以我猜想如果我从中减去幻数48可以使用它.
But it DOES account for any object creation so I guess I could use this if I subtract the magic number 48 from it.
推荐答案
您可以使用Java代理来执行此操作,可以通过作者的博客找到开放源代码实现-
you can use a Java agent to do this, open source implementation can be found via the author's blog - http://jeremymanson.blogspot.co.uk/2012/02/update-to-allocation-instrumenter.html
这篇关于由于freeMemory()仅报告长期存在的对象,因此如何跟踪Java中的任何对象创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!