I’m trying to delete a file that another thread within my program has previously worked with.
I’m unable to delete the file but I’m not sure how to figure out which thread may be using the file.
So how do I find out which thread is locking the file in java?
I don’t have a straight answer (and I don’t think there’s one either, this is controlled at OS-level (native), not at JVM-level) and I also don’t really see the value of the answer (you still can’t close the file programmatically once you found out which thread it is), but I think you don’t know yet that the inability to delete is usually caused when the file is still open. This may happen when you do not explicitly call
Closeable#close()on theInputStream,OutputStream,ReaderorWriterwhich is constructed around theFilein question.Basic demo:
In other words, ensure that throughout your entire Java IO stuff the code is properly closing the resources after use. The normal idiom is to do this in the
try-with-resourcesstatement, so that you can be certain that the resources will be freed up anyway, even in case of anIOException. E.g.Do it for any
InputStream,OutputStream,ReaderandWriter, etc whatever implementsAutoCloseable, which you’re opening yourself (using thenewkeyword).This is technically not needed on certain implementations, such as
ByteArrayOutputStream, but for the sake of clarity, just adhere the close-in-finally idiom everywhere to avoid misconceptions and refactoring-bugs.In case you’re not on Java 7 or newer yet, then use the below
try-finallyidiom instead.Hope this helps to nail down the root cause of your particular problem.