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[]右鍵菜單選擇【生成快照並顯示棧分配跟蹤】。能夠快速定位在什麼地方消耗比較大的內存,能夠快速解決問題: