Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

Java Memory leaks with FileChannel

1 min read

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.

IDRsolutions develop a Java PDF Viewer and SDK, an Adobe forms to HTML5 forms converter, a PDF to HTML5 converter and a Java ImageIO replacement. On the blog our team post anything interesting they learn about.

Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

Java 13 Articles-series index

Here at IDRsolutions we always like to research and test the key new features in each Java release, as well as some of the hidden...
Madalena
28 sec read

Why we wrote our own Java jpeg2000 libraries

JPEG2000 is an important image file format which offers significant benefits over JPEG. For our specific usage it does generate significantly smaller file sizes...
Mark Stephens
52 sec read

Leave a Reply

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

IDRsolutions Ltd 2019. All rights reserved.