we're facing a memory leak using a simple, simple, simple code as follows. The code is intended to get files from a source, use each file to do something and go on. This simple code uses always the same file but the behaviour is unchanged.
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;
}
}
Now... we just can't see a valid reason for this code to consume memory up to the top and in the end throws an OutOfMemoryError exception.
Any idea?
Something More
The problem arises using Java Development Kit Version 6 Update 23 but it does not on JRE 1.7