JDK-8295368 : File.delete is not working as expected
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.io
  • Affected Version: 11.0.11
  • Priority: P4
  • Status: Open
  • Resolution: Unresolved
  • OS: windows
  • Submitted: 2022-10-14
  • Updated: 2022-10-15
Description
File.delete() API returns true but in next API call to check check if the file exists, i.e., File.exists(), also returns true even after File.delete() execution has returned.
This is causing failure to delete the root directory.

Below is the code implementation:
-------------------------------------------------
public static void deleteDirrectoryAndContents(File file) throws IOException
{
Files.walk(file.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile)
.forEach(f -> {
boolean isDeleted = f.delete();
if (f.exists() && isDeleted) {
System.out.println("f.exists:" + f.exists());
System.out.println("isDeleted:" + isDeleted);
System.out.println("file/directory:" + f.getAbsolutePath());
}else {
System.out.print("Deleted Item Count:"+(++deletedFileCount)+"\r");
}
});
}

In the above code snippet, f.delete() returns true but in the next code statement f.exists() also returns true. When we checked the file system after a few seconds, the file is already deleted. However, the root directory is not deleted as it suspects that the directory is not empty.

Adding a wait of 20-30 seconds after f.delete() method did the trick and the root directory is deleted as expected from the code.

This issue appears mostly in 2-core VMs and in a few 4-core VMs. It is not replicable in highly configured systems. We also observed that CPU utilization was showing 100% during the entire process.
Comments
Thanks for updating the bug to make it clear that this is Windows. You may wish to looking into FILE_DISPOSITION_POSIX_SEMANTICS to see if it changes anything.
15-10-2022

According to the submitter's triaging process, this issue was duplicated majorly in Windows. Based on Windows API Doc at https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-deletefile, after running the file delete operation in Java, then immediately checking if the file gets deleted, it is most likely the checking will return true in Java API.
14-10-2022

A similar issue was reported also at https://bugs.openjdk.org/browse/JDK-8208355
14-10-2022

It would be useful to update this bug to indicate which operating system and file system this is.
14-10-2022