java内存泄露原因_Java内存泄露的原因

Java内存泄露的原因

1、静态集合类像HashMap、Vector等的使用最容易出现内存泄露,这些静态变量的生命周期和应用程序一致,所有的对象Object也不能被释放,因为他们也将一直被Vector等应用着。

这种情况可以通过remove clear方式释放对象,没有问题。

2、数据库的连接没有关闭情况,包括连接池方法连接数据库,如果没有关闭ResultSet等也都可能出现内存泄露的问题。

这是代码中经常出现的问题。

3、内部类和外部类的引用容易出现内存泄露的问题;监听器的使用,java中往往会使用到监听器,在释放对象的同时没有相应删除监听器的时候也可能导致内存泄露。

我认为此说法是不准确, 及时将对象设置为null可以加快内存回收,但并不代表内存不可达或者泄露,我们使用一个例子来验证下

packagetestawt;importjava.io.Console;importjava.util.Scanner;importjava.util.Vector;classperson

{publicString name;publicString age;privatehand handhello;publicperson ()

{

handhello=new hand(this);

}public voidsayhello()

{

handhello.Shake();

}public voidfinalize()

{

System.out.println("gc person!");

}

}classhand

{privateperson per;publichand(person per)

{this.per=per;

}public voidShake()

{

System.out.println("Shake!");

}public voidfinalize()

{

System.out.println("gc hand!");

}

}public classtestm {private staticScanner in;public static voidmain(String[] args)

{

Vector v = new Vector();for (int i = 1; i<20; i++)

{

person o= newperson();

v.add(o);

}

v.clear();

System.gc();//所有对象释放了

in = newScanner(System.in);int a =in.nextInt();for (int i = 0; i < 10; i++) System.out.println(a+i);

}

}

person和hand存在相互引用。但是强制调用gc ,能够回收内存。

gc person!

gc hand!

gc person!

gc hand!

gc person!

3、大量临时变量的使用,没有及时将对象设置为null也可能导致内存的泄露

我认为此说法不准确,及时将对象设置为null可以加快内存回收,但并不代表内存不可达或者泄露,如果你觉得自己使用了大量的临时变量,可以自己强制执行一次System.gc();

importjava.io.Console;importjava.util.Scanner;importjava.util.Vector;classperson

{publicString name;publicString age;publichand handhello;public voidfinalize()

{

System.out.println("gc person!");

}

}classhand

{public voidhello()

{

System.out.println("hello!");

}public voidfinalize()

{

System.out.println("gc hand!");

}

}classfooter

{public voidwalk()

{

System.out.println("walk!");

}public voidfinalize()

{

System.out.println("gc footer !");

}

}public classtestmain {private staticScanner in;public static voidmain(String[] args)

{//TODO Auto-generated method stub

Vector v = new Vector();for (int i = 1; i<20; i++)

{

person o= newperson();

o.handhello=newhand();

v.add(o);

footer f=newfooter();

f.walk();//o = null;

}

v.clear();

System.gc();//所有对象释放了

in = newScanner(System.in);int a =in.nextInt();for (int i = 0; i < 10; i++) System.out.println(a+i);

}

}

运行结果

gc footer !

gc hand!

gc person!

gc footer !

gc hand!

gc person!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值