we encounter a memory leak using simple, simple and simple code as follows. The code is designed to receive files from the source, use each file to do something and continue. This simple code always uses the same file, but the behavior does not change.
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();
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
return bytes;
}
}
Now ... we just don’t see a real reason for this code to consume memory to the top and ultimately throw an OutOfMemoryError exception.
Any idea?
Something more.
The problem occurs using the Java Development Kit version 6 Update 23, but not on JRE 1.7
source
share