Release Java file lock in Windows

This is a known Bug in Java on Windows, please see Bug #4715154

Sun evaluated the problem and closed the bug with the following explanation:

We cannot fix this. Windows does not allow a mapped file to be deleted. This problem should be ameliorated somewhat once we fix our garbage collectors to deallocate direct buffers more promptly (see 4469299), but otherwise there's nothing we can do about this.


Adding to mhaller's answer

And translating sarumont's comment into code

This should/may work.

private static void deleteMappedFilesIfExists(Path path) throws IOException {
    while (true) {
        try {
            Files.deleteIfExists(path);
            break;
        } catch (AccessDeniedException e) {
            System.gc();
        }
        //Add delay if needed.
    }
}

Tags:

Java

File Io