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.

Two issues with Java File access for temporary files

51 sec read

In theory, Java has a very flexible and powerful set of commands for manipulating Files. The File object allows you create a File or Directory, access alsorts of information about it and also delete it. The problem we find, however, is that it is not always possible to delete a file in Java by using file.delete(), even if you created it. Especially on Windows, Java retains a lock on the files and will not delete the file in the session – even if you created it. This can be a real issue if you create lots of temporary files which need to be cleaned up. You can create a File with a deleteOnExit() call, but if the program is expected to run continually, this will create a memory leak and not ever delete the files.

So we added a work around, checking in the next session for old files and deleting them so keep our temp directory clean. This exposes a second issue – the lastModified() method seems to be incredibly inefficient. In our tests, on systems with lots of files, this function alone was accounting for 30% of the CPU usage in a process which opened PDFs decoded them, rasterized them and then deleted them. 

So if you are using File commands for temporary files, be careful to ensure they are deleted, and try to have small numbers of files if you need to access their timestamp.

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 *