我们使用如下简单、简单、简单的代码面临内存泄漏。该代码旨在从源获取文件,使用每个文件做某事并继续。这个简单的代码总是使用相同的文件,但行为没有改变。
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 Development Kit Version 6 Update 23 会出现问题,但在 JRE 1.7 上没有