VisualVM是集成了多个JDK命令工具的一个可视化工具,它主要用来监控JVM的运行情况,可以用它来查看和浏览Heap Dump、Thread Dump、内存对象实例情况、GC执行情况、CPU消耗以及类的装载情况。在JDK Update7之后,VisualVM作为JDK的一部分发布,但同时VisualVM也发布独立的版本。VisualVM必须运行在JDK1.6以上的VM环境下,但可以用它来监控JDK1.4以上的JVM。
1:创建java工程VisualvmTest,写一个消耗内存的测试代码:
2:在MemoryLeak.java右键菜单选择【Profile As】->【Java Application】,在弹出如下窗口,选择【memory】.
3:程序开始启动运行,同时弹出visualvm窗口,如下图,【profile】tab可以看到对象大小比例。【监控】可以看到对的运行走向。
4:可以发现byte数组暂用比较大。在byte[]右键菜单选择【生成快照并显示栈分配跟踪】。能够快速定位在什么地方消耗比较大的内存,能够快速解决问题:
参考资料: VisualVM远程监控
1:创建java工程VisualvmTest,写一个消耗内存的测试代码:
- publicclassMemoryLeak{
- publicstaticvoidmain(String[]args)throwsInterruptedException{
- intMAX_CONSUMERS=10000;
- intSLEEP_BETWEEN_ALLOCS=5;
- ConsumerContainerobjectHolder=newConsumerContainer();
- while(objectHolder.size()<MAX_CONSUMERS){
- System.out.println("Allocatingobject"
- +Integer.toString(objectHolder.size()));
- objectHolder.add(newMemoryConsumer());
- try{
- Thread.currentThread().sleep(SLEEP_BETWEEN_ALLOCS);
- }catch(InterruptedExceptionie){
- //Donothing.
- }
- }//while.
- Thread.sleep(1000*60*60);
- }//main.
- }//EndofMemoryLeak.
- classConsumerContainerextendsVector{
- }
- classMemoryConsumer{
- publicstaticfinalintMEMORY_BLOCK=1024;
- publicbyte[]memoryHoldingArray;
- MemoryConsumer(){
- memoryHoldingArray=newbyte[MEMORY_BLOCK];
- }
- }//EndMemoryConsumer.
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[]右键菜单选择【生成快照并显示栈分配跟踪】。能够快速定位在什么地方消耗比较大的内存,能够快速解决问题:
参考资料: VisualVM远程监控