jmap
jmap 命令查看内存中对象的数量,统计内存泄漏。
命令为:jps ==》 jmap -histo:live 进程号 > 1.txt (内存中对象的数量统计写入1.txt文件中);使用jmap -histo[:live] pid查看堆内存中的对象数目、大小统计直方图,如果带上live则只统计活对象;
在泛型的篇章中,其中遇到了一些问题:
通过查询了解到,如果指定的进程是在64位Java虚拟机(JVM)上运行,那么你可能需要指定-J-d64选项,例如:jmap -J-d64 -histo:live 进程号。如果依旧不行,cmd查看你的java版本,命令:java ===》java -version。看你的JVM是否为64位,如果不是请进行重新下载。
jmap -J-d64 -histo:live 进程号
例:写一个泛型栈。
class GenericStack<T>{
private T[] elem;//定义一个T类型的数组
private int top;
public GenericStack(){
this(10);
}
public GenericStack(int size){
this.elem = (T[]) new Object[size];
this.top = 0;
}
public void push(T val){ //T类型的参数
this.elem[this.top ++] = val;
}
public void pop(){
--this.top;
}
public T getTop(){
return this.elem[this.top-1];
}
}
class Animal{
}
public class GenericStackDemo {
public static void main(String[] args) throws InterruptedException {
GenericStack<Animal> genericStack = new GenericStack<Animal>();
genericStack.push(new Animal());
genericStack.push(new Animal());
genericStack.push(new Animal());
genericStack.pop();
System.gc();//回收
Thread.sleep(100000);
}
}
在代码中入栈了三次,出栈一次,在使用命令查看内存中对象时仍有3个,说明只是栈顶指针下移,并没有释放内存。
解决办法:在出栈时将栈顶指针的下一个指定为null,之后再次使用jmap 命令查看内存中对象的数量,统计内存泄漏,之后发现出栈一次后,内存中存在对象只剩两个。
public void pop(){
this.elem[this.top - 1] = null;
--this.top;
}