非常感谢此博主博客,助我解决了bug,博客地址如下
http://blog.youkuaiyun.com/kingzone_2008/article/details/45015301
最近出现了个这上面的异常,报错异常是说–>变量初始化出现问题,通常出现在静态变量尤其是单例模式。这种问题往往是初始化顺序不对造成的!
报错代码如下:
public class InvestPeopleRes {
private static List<InvestPeople> investPeopleList ;
//静态代码块 在jvm在加载类的时候,就已经在执行加载了
static {
investPeopleList = new ArrayList<>();
investPeopleList.add(new InvestPeople("2016-04-06 23:15", 2000.00f, "135******41"));
investPeopleList.add(new InvestPeople("2016-05-06 08:15", 100.00f, "133******85"));
investPeopleList.add(new InvestPeople("2016-05-05 17:15", 12430.00f, "136******55"));
}
//外界方法调用时,返回对象
public static List<InvestPeople> getInvestPeopleList() {
return investPeopleList;
}
}
即当程序在加载的时候,就会出现investPeopleList 对象的内存泄漏! 解决方案只需要解决investPeopleList对象初始化的问题即可!
方案如下:将investPeopleList 对象初始化放在构造器中其就ok
public class InvestPeopleRes {
private static List<InvestPeople> investPeopleList ;
//无参数构造器
public InverstPeopleRes(){
investPeopleList = new ArrayList<>();
investPeopleList.add(new InvestPeople("2016-04-06 23:15", 2000.00f, "135******41"));
investPeopleList.add(new InvestPeople("2016-05-06 08:15", 100.00f, "133******85"));
investPeopleList.add(new InvestPeople("2016-05-05 17:15", 12430.00f, "136******55"));
}
//外界方法调用时,返回对象
public static List<InvestPeople> getInvestPeopleList() {
return investPeopleList;
}
}
更加详细的类的执行顺序,请参考博客
http://blog.youkuaiyun.com/kingzone_2008/article/details/45015301
以上!谢谢
本文介绍了一种在Java中遇到的静态变量初始化错误,并提供了解决方案。通过将静态变量的初始化从静态代码块移至构造函数中,可以避免因初始化顺序不当导致的内存泄漏问题。
639

被折叠的 条评论
为什么被折叠?



