次のようなシンプルでシンプルなコードを使用すると、メモリ リークが発生します。このコードは、ソースからファイルを取得し、各ファイルを使用して何かを実行し、続行することを目的としています。この単純なコードは常に同じファイルを使用しますが、動作は変わりません。
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 では発生しません。