gpt4 book ai didi

Java不释放内存

转载 作者:行者123 更新时间:2023-12-02 00:00:21 25 4
gpt4 key购买 nike

我有一个守护程序,它读取文件的内容,然后将其压缩并将其写入较小的 .tar.gz 文件。

出于某种原因,Java 会继续分配内存,即使在我释放(或者我认为我已经释放)所有已用内存之后也是如此。我的代码/推理有什么问题?

FileOutputStream fos    = null;
GZIPOutputStream gzipos = null;
OutputStreamWriter osw = null;

BufferedWriter bw = null;
while (true) {
if (f.length() != 0) {
if (outputfile == null) {
outputfile = outputfileroot + "_" + outputPart + ".tar.gz";

fos = new FileOutputStream(outputfile);
gzipos = new GZIPOutputStream(fos);
osw = new OutputStreamWriter(gzipos);
bw = new BufferedWriter(osw);
}
else if (new File(outputfile).length() > maxLengthOutputFile) {
bw.flush();
osw.flush();
gzipos.flush();
fos.flush();
bw.close();
osw.close();
gzipos.close();
fos.close();

bw = null;
osw = null;
gzipos = null;
fos = null;

System.gc();

System.out.println("Finished writing " + outputfileroot + "_" + outputPart + ".tar.gz");

outputfile = outputfileroot + "_" + ++outputPart + ".tar.gz";
fos = new FileOutputStream(outputfile);
gzipos = new GZIPOutputStream(fos);
osw = new OutputStreamWriter(gzipos);
bw = new BufferedWriter(osw);
}

/**
* Read the entire file
*/
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
// will send the content to another thread, so I need to read it line by line
bw.write(line + "\r\n");
}
br.close();
br = null;
bw.flush();

/**
* Empty it
*/
FileWriter fw = new FileWriter(f);
fw.write("");
fw.flush();
fw.close();
fw = null;
}

Thread.sleep(1000);
}

最佳答案

你把这个煮过头了。所有这些 null 设置和 gc() 调用实际上并没有帮助,而且您的刷新和关闭次数是您真正需要的数倍。此外,您根本不需要使用 Readers 和 Writers。所有这些都可以简化为:

GZIPOutputStream gzipos = null;
while (true)
{
if (f.length() != 0)
{
if (outputfile == null)
{
outputfile = outputfileroot + "_" + outputPart + ".tar.gz";
gzipos = new GZIPOutputStream(new FileOutputStream(outputfile));
}
else
{
if (new File(outputfile).length() > maxLengthOutputFile)
{
gzipos.close();
System.out.println("Finished writing " + outputfileroot + "_" + outputPart + ".tar.gz");
outputfile = outputfileroot + "_" + ++outputPart + ".tar.gz";
gzipos = new GZIPOutputStream(new FileOutputStream(outputfile));
}
}

/**
* Read the entire file
*/
InputStream in = new FileInputStream(f);
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 0)
{
gzipos.write(buffer, 0, count);
}
in.close();
gzipos.flush();
/**
* Empty it
*/
f.createNewFile();
}
Thread.sleep(1000);
}

我无法理解你的评论“将把内容发送到另一个线程,所以我需要逐行阅读它”。此代码中没有线程,您不需要逐行输入。

我也很好奇它如何与生成输入文件的任何内容交互。我认为您应该在决定复制输入文件后立即重命名输入文件,并在其位置创建一个新的空文件,而不是在复制步骤之后。

关于Java不释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14963626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com