I have code which deletes all of the files in a directory except for the last n most recently modified ones. The code gets a list of File
objects from a directory, sorts them using a comparator which looks at File.lastModifedTime()
, then deletes the appropriate sublist.
When we upgraded to Java 7, the program started throwing java.lang.IllegalArgumentException: Comparison method violates its general contract!
. I suspect that this is because a file is modified (normal behavior) before sorting is completed so the comparator is returning inconsistent values as it check each file's last modified time.
My question is, how would you solve this problem and delete the right files?
One suggestion I read was to store the file and it's last modified time in a map before sorting so when comparisons are done, the last modified time is looked up from the map. However, if the file changed mid sort, the map isn't updated so wouldn't you end up deleting the wrong file?
Other idea I thought of was using Java NIO's file watch to keep a sorted list and re-sort whenever a file changes. But that seems fairly complicated.
I also thought of a brute force method of wrapping the sort in a try-catch statement and just retry the whole sort if it runs into the comparison method violation.
Lastly, I could just set the java.util.Arrays.useLegacyMergeSort
property and go back to the silently ignore ways of Java 6.