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.

Are you a Java Developer working with PDF files?

Find out why you should be using JPedal

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.



Our software libraries allow you to

Convert PDF to HTML in Java
Convert PDF Forms to HTML5 in Java
Convert PDF Documents to an image in Java
Work with PDF Documents in Java
Read and Write AVIF, HEIC, WEBP and other image formats
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.