I am reading a bunch of binary files (one at a time) into memory to perform some operations on them and then saving them back to the disk. With small files, it works perfectly fine, however, with larger files there is quite a bit of concern that I have.
Now, assuming that the file I am reading is 25Mb large - this is what my code looks like:-
public static byte[] returnEncryptedFileData(File fileObj) {
byte[] fileData = FileUtils.readFileToByteArray(fileObj);
//now performing some operations on fileData
return fileData;
}
Right after this code executes, I see (50Mb + MISC) of extra space consumption (which is fine because there would be 2 byte arrays - one is fileData as I've defined and another one used by readFileToByteArray to perform the operation, each holding 25Mb of data)
However, even after this method returns and is called again for the next file to be read, the memory held previously isn't released! If the next file being read is 30Mb large, I see a memory consumption of (50Mb + 60Mb + MISC)
How do I cleanup after reading the file to a byte array, performing some operations on it and then return it from a method. System.gc() doesn't help as it does not execute the GC right away.. no way that I believe exists to "deallocate" memory?
What am I doing wrong here?