Search code examples
javamultithreadingfile-locking

How to find out which thread is locking a file in java?


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?


Solution

  • 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 the InputStream, OutputStream, Reader or Writer which is constructed around the File in question.

    Basic demo:

    public static void main(String[] args) throws Exception {
        File file = new File("c:/test.txt"); // Precreate this test file first.
        FileOutputStream output = new FileOutputStream(file); // This opens the file!
        System.out.println(file.delete()); // false
        output.close(); // This explicitly closes the file!
        System.out.println(file.delete()); // true
    }
    

    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-resources statement, so that you can be certain that the resources will be freed up anyway, even in case of an IOException. E.g.

    try (OutputStream output = new FileOutputStream(file)) {
        // ...
    }
    

    Do it for any InputStream, OutputStream, Reader and Writer, etc whatever implements AutoCloseable, which you're opening yourself (using the new keyword).

    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-finally idiom instead.

    OutputStream output = null;
    try {
        output = new FileOutputStream(file);
        // ...
    } finally {
        if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
    }
    

    Hope this helps to nail down the root cause of your particular problem.