1

This question already was asked here. But the proposed solutions there are not satisfying/do not work as promised.

The problem (delete the enclosing directory after having deleted the one file in the dir occasionaly does not work) is still present in java 8, regardless if the file stream is flushed, closed, set to null, System.gc() or Thread.yield() etc. is called. Just a retry after a short sleep is successful.

Here is a small test program which prooves the problem:

public static void main(String args[])
{
    int run = 0;

    try
    {
        File dir = new File("c:\\testdir");

        for (run = 0; run < 10000; run++)
        {
            dir.mkdirs();

            File file = new File(dir, "testfile.txt");
            FileOutputStream str = new FileOutputStream(file);
            ObjectOutputStream ostr = new ObjectOutputStream(str);
            {
                ostr.writeObject(Boolean.FALSE);
            }

            ostr.flush();
            ostr.close();
            ostr = null;
            str.flush();
            str.close();
            str = null;

            Thread.yield();
            System.gc();

            int retries = 10;
            int dretries = 10;

            while (! file.delete())
            {
                if (--retries > 0)
                {
                    Thread.sleep( 10);
                }
                else
                {
                    throw new Exception( "file.delete");
                }
            }

            while (! dir.delete())
            {
                if (--dretries > 0)
                {
                    Thread.sleep( 10);
                }
                else
                {
                    throw new Exception( "dir.delete");
                }
            }

            if (retries != 10 || dretries != 10)
            {
                System.out.println( "loop:" + run + " - retries:" + retries + " - dretries:" + dretries);
            }

            if (run % 200 == 0) System.out.println( "loop:" + run);
        }
    }
    catch (Throwable t)
    {
        t.printStackTrace();
    }

    System.out.println("run:" + run);
}

What can be done to get rid of this annoying problem?

Heri
  • 4,368
  • 1
  • 31
  • 51

0 Answers0