Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java keeps lock on files for no apparent reason

Tags:

java

file

locking

Despite closing streams in finally clauses I seem to constantly run into cleaning up problems when using Java. File.delete() fails to delete files, Windows Explorer fails too. Running System.gc() helps sometimes but nothing short of terminating the VM helps consistently and that is not an option.

Does anyone have any other ideas I could try? I use Java 1.6 on Windows XP.

UPDATE: FLAC code sample removed, the code worked if I isolated it.

UPDATE: More info, this happens in Apache Tomcat, Commons FileUpload is used to upload the file and could be the culprit, also I use Runtime.exec() to execute LAME in a separate process to encode the file, but that seems unlikely to cause this since ProcessExplorer clearly indicates that java.exe has a RW lock on the file and LAME terminates fine.

UPDATE: I am working with the assumption that there is a missing close() or a close() that does not get called somewhere in my code or external library. I just can't find it!

like image 418
Jonas K Avatar asked Feb 25 '09 16:02

Jonas K


2 Answers

The code you posted looks good - it should not cause the issues you are describing. I understand you posted just a piece of the code you have - can you try extracting just this part to a separate program, run it and see if the issue still happens? My guess is that there is some other place in the code that does new FileInputStream(path); and does not close the stream properly. You might be just seeing the results here when you try to delete the file.

like image 80
Bogdan Avatar answered Oct 18 '22 15:10

Bogdan


I assume you're using jFlac. I downloaded jFlac 1.3 and tried your sample code on a flac freshly downloaded from the internet live music archive. For me, it worked. I even monitored it with ProcessExplorer and saw the file handles be opened and then released. Is your test code truly as simple as what you gave us, or is that a simplified version of your code? For me, once close() was called, the handle was released and the file was subsequently successfully deleted.

Try changing your infinite loop to:

File toDelete = new File(path);
if (!toDelete.delete()) {
  System.out.println("Could not delete " + path);
  System.out.println("Does it exist? " + toDelete.exists());
}

or if you want to keep looping, then put a 1 second sleep between attempts to delete the file. I tried this with JDK6 on WinXP Pro.

Don't forget to put a try/catch around your close() and log errors if the close throws an exception.

like image 36
Eddie Avatar answered Oct 18 '22 14:10

Eddie