Site iconJava PDF Blog

Java Memory leaks with FileChannel

It is a myth that Java has no ‘memory leaks’. It is certainly much better than developing in C and many of the gotchas do not exist in Java. But there are still potential memory issues in Java.

For example, we have been looking at using FileChannel. This allows the developer to have only part of a huge byte Buffer in memory, store the whole thing in a File on disk and let Java handle caching seemlessly for you. It is really great, but there appears to be an error in some versions of Java where the File on disk is never actually deleted. Despite closing everything, there is still some Lock stopping Java from being able to delete it. So we have gone back to using a RandomAccesFile and manually reading the blocks we need (which is a shame but the only pragmatic solution).

Files objects in Java particularly seem to cause these sorts of issues. You can tell Java to delete a File on the disk, but there is no guarantee it will be deleted if there is still a Lock on it. And if you use the File.deleteOnExit() and the program never exits, you will get a leak as the Files and memory handles accumulate.

Every class can have a finalize() method. It is called last when the object is being destroyed. This is quite slow and should only be used sparingly. But it is an ideal place to ensure files are deleted.

So be aware, Java has fewer memory leak issues and stops lots of bad practices but there are still problems which can crop up, especially where you access actual physical objects such as files.