我编写了一个简单的程序来理解VisualVM是如何工作的。下面是完整的代码:
package memorygames;
public class MemoryGames
{
static class A {
private int i;
private String s;
A(int i, String s)
{
this.i = i;
this.s = s;
}
public int getI()
{
return i;
}
public String getS()
{
return s;
}
}
public static void main(String[] args) {
A a = new A(23, "hello");
while(true) {
System.out.println(a.getS());
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}现在,我用VisualVM为我的应用程序创建了一个HeapDump。我看到了'A‘类的实例,但是s变量是空的!其值等于null。'i‘变量保存正确的值23。
为什么会发生这种情况?
更新:可能是我误用了VisualVM?这是我的屏幕截图:http://oi42.tinypic.com/2091qfl.jpg
更新:不确定,但这可能是内存优化的结果。我已经添加了
while(true) {
a.setS(new String("a-setter " + Math.random()));
(...)
}..。现在我可以在变量中看到字符串值了。我想知道其他人是否真的可以在堆中看到与我不同的结果。
发布于 2013-09-26 13:53:59
这可能是您用来运行示例的JDK的问题。您可以尝试不同版本的JDK吗?JDK 7u40或JDK 8预览构建?它适用于我使用JDK 7u40。
https://stackoverflow.com/questions/19007614
复制相似问题