我们正在面对一个简单,简单,简单的代码如下所示的内存泄漏。 该代码旨在从源获取文件,使用每个文件做一些事情并继续。 这个简单的代码总是使用相同的文件,但行为不变。现在FileInputStream内存泄漏文件读取循环
package it.datapump.main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class TifReader {
public static void main (final String[] a){
for (int i = 0; i < 100000; i++) {
try {
getBytesFromFile(new File("test.tif"));
Thread.sleep(1000);
System.gc() ;
} catch (Exception ex) {
}
}
}
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
long length = file.length();
byte[] bytes = new byte[(int)length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
is.close();
// Do something with the read bytes
//
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
return bytes;
}
}
...我们不能看到这个代码,以消耗内存到顶部,并最终抛出一个OutOfMemoryError异常的正当理由。
有什么想法?
更多的东西
问题就出现了使用Java开发套件版本6更新23,但它不会对JRE 1.7
我是否正确 - 正确* this * snippet创建了一个OOM错误,OOM与注释的“使用读取字节做某事”部分没有关系?没有例外被抛出? – 2011-02-02 09:24:32
@Andreas_D,没有兴趣分析片段。这是完全错误的阅读文件的方式。 – 2011-02-02 09:25:53
@Vladimir:恕我直言,你需要尊重OP发布的问题,而不是强迫你通过。顺便说一句,这不是一个错误的方式,它只是一种循环方式。 – 2011-02-02 09:30:45