I have a Java method that looks at a folder on Windows share and delete any sub folder whose modification timestamp is 2 days or more ago. Basically delete stale directories as this is a staging folder where other threads in the process queue up jobs and delete job folder once done. Sometimes the process could get terminated and leave behind jobs in progress. This method gets called in next session to clear the stale sub dirs.

Below is code snippet that does this. I am running into FileNotFoundException while Files.walk() is returning all the sub dirs. That is possible as other threads in the process could be deleting folders that Files.walk() is trying to look at. I don't want to synchronize between those threads and this method.

I am wondering if there is a better way to do this to mitigate these exceptions.

public int purgeStaleContent()
{
    int result = 0;
    try {
        Path jobRoot = "\\\\apollo\\dropbox\\jobs";
        List<Path> signDirs = Files.walk(jobRoot).filter(Files::isDirectory).collect(Collectors.toList());
        for(Path signDir: signDirs)
        {
            Logger.getGlobal().info("Checking job dir: "+signDir);
            FileTime lastModified = Files.getLastModifiedTime(signDir);
            if (Duration.between(lastModified.toInstant(), Instant.now()).toDays() > 2)
            {
                FileUtils.deleteDirectory(signDir.toFile());
                Logger.getGlobal().info("Deleted stale job dir: "+signDir);
                result++;
            }
        }
    }
    catch (IOException ex) {
        Logger.getGlobal().log(Level.SEVERE, "Got exception while purging stale content in job dir" , ex);
        }
    }
    return result;
}

I am new to Java NIO package and its services. If this can be accomplished using Apache commons or native Java File IO support, that is fine as well. This app has to run on Java 8 JRE.

0

There are 0 best solutions below