我最近开始学习Java(现在有了额外的空闲时间),并使用Netbeans 8.2为名为torn的游戏编写了代码。此代码是可运行的,可连续从站点检索数据并将其存储以供以后使用。运行过程中冻结了,有人告诉我为URL连接添加连接超时和读取超时可能会有所帮助。我这样做了,它目前又在运行(到目前为止很好),并且正在等待,看看该问题是否会再次发生。
我的问题关于寻找内存泄漏。我读到幸存的世代数是是否存在内存泄漏的指标。运行数小时后,这是遥测的screenshot。 The code for the project也可用(OtherFactionsStats.java是主类)。 (也欢迎任何有关改进我的代码的说明:D)。感谢您的帮助。
[我认为我终于找到了您的资源泄漏:在第154行的LogFactionPersonalStat
中,您使用in = new BufferedReader(...
打开了一个永不关闭的文件。
我建议您学习try with resources。
同一文件中的代码,例如从第128行到第130行的更改为
FileWriter file = new FileWriter("" + path + completed); //set completion status to incomplete
file.write("0"); //zero means not yet complete
file.close();
to
try (FileWriter file = new FileWriter("" + path + completed)) { //set completion status to incomplete
file.write("0"); //zero means not yet complete
}
不是很大的变化,但是现在您不能忘记关闭FileWriter
(或BufferedWriter
或BufferedReader
)
另一注:RunUpdate
53行看起来非常可疑(此模式重复了几次):
Logger.getLogger("Error reading from file");
这里您为“错误读取文件”创建了一个骗子,但您从未使用该记录器将任何内容写入日志。
您可能想写类似的东西
Logger.getLogger(OtherFactionsStats.class.getName()).severe("Error: Possible timeout or problems with file");
或
Logger.getLogger(OtherFactionsStats.class.getName()).log(Level.Severe, "Error: Possible timeout or problems with file");