1:创建java工程VisualvmTest,写一个消耗内存的测试代码:
public class MemoryLeak {
public static void main(String[] args) throws InterruptedException {
int MAX_CONSUMERS = 10000;
int SLEEP_BETWEEN_ALLOCS = 5;
ConsumerContainer objectHolder = new ConsumerContainer();
while (objectHolder.size() < MAX_CONSUMERS) {
System.out.println("Allocating object "
+ Integer.toString(objectHolder.size()));
objectHolder.add(new MemoryConsumer());
try {
Thread.currentThread().sleep(SLEEP_BETWEEN_ALLOCS);
} catch (InterruptedException ie) {
// Do nothing.
}
} // while.
Thread.sleep(1000*60*60);
} // main.
} // End of MemoryLeak.
class ConsumerContainer extends Vector {
}
class MemoryConsumer {
public static final int MEMORY_BLOCK = 1024;
public byte[] memoryHoldingArray;
MemoryConsumer() {
memoryHoldingArray = new byte[MEMORY_BLOCK];
}
} // End MemoryConsumer.
2:在MemoryLeak.java右键菜单选择【Profile As】->【Java Application】,在弹出如下窗口,选择【memory】.
3:程序开始启动运行,同时弹出visualvm窗口,如下图,【profile】tab可以看到对象大小比例。【监控】可以看到对的运行走向。
4:可以发现byte数组暂用比较大。在byte[]右键菜单选择【生成快照并显示栈分配跟踪】。能够快速定位在什么地方消耗比较大的内存,能够快速解决问题: