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.

Related Posts:

The following two tabs change content below.

Mark Stephens

System Architect and Lead Developer at IDRSolutions
Mark Stephens has been working with Java and PDF since 1999 and has diversified into HTML5, SVG and JavaFX. He also enjoys speaking at conferences and has been a Speaker at user groups, Business of Software, Seybold and JavaOne conferences. He has a very dry sense of humor and an MA in Medieval History for which he has not yet found a practical use.
Markee174

About Mark Stephens

Mark Stephens has been working with Java and PDF since 1999 and has diversified into HTML5, SVG and JavaFX. He also enjoys speaking at conferences and has been a Speaker at user groups, Business of Software, Seybold and JavaOne conferences. He has a very dry sense of humor and an MA in Medieval History for which he has not yet found a practical use.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>