A Web application runs on tomcat server, creates a temp files and deletes it once its usage over, but some error scenarios temp files are not being deleted. which are stacked up and never deleted. Used deleteOnExit() seems not working, after tomcat server shutdown also these temp files still exisitng in system.
The error of the files not deleted looks like some process still holds lock on that, so planning to write a thread/scheduler class which queue all these error temp files and re-tries until these are deleted sucessfully from system..
ShutdownHook is similar to my thought but the only drawback i am seeing is it only runs on shutdown, is their any best practices available to this problem. Any suggestions.
You do not want to use File.deleteOnExit()
: your web application should run for months without exiting the JVM, right? Instead, you need to clean-up after yourself properly.
Use File.delete()
and check the return status (it returns a boolean
: check it). If that returns false
, figure out why that's happening. For instance, if you are on Windows, there are some (IMO foolish) restrictions on deleting files that are opened by a live process -- including the process trying to delete them. So, if you have another thread that has a file handle to the file you are trying to delete, you are not going to be able to delete the file.
So, what is holding-open that file lock? Find that and fix it. Specifically, make sure that you have properly-closed all your file handles (did you use finally
blocks? If no, you're doing it wrong) and that you aren't trying to do something silly like dynamically-generate a file, save it to the disk, have Tomcat serve it using the DefaultServlet
, and then delete the file.
If you can't manage to make the file-deletion work synchronously, then maybe try asynchronous deletion: keep a queue of files to delete (maybe in the application
scope) and process them every few minutes. Just try to delete each one and, if the deletion succeeds, remove it from the queue. If the queue exceeds some size, automatically send an email to an administrator to complain about the size of the queue.