[
Date Prev][
Date Next][
Thread Prev][
Thread Next][
Date Index][
Thread Index]
Re: bug in diskcache?
- Subject: Re: bug in diskcache?
- Date: Thu, 03 Jun 2010 16:40:06 -0600
On 6/3/2010 2:33 PM, Steve Ansari wrote:
Hi John,
I think I found a bug in the DiskCache comparators:
The problem is a truncation issue when casting from long to int.
In DiskCache.java, line 346, 'FileAgeComparator'
Here is the problem line:
return (int) (f2.getTime() - f1.getTime());
Here is a fix:
return (f2.getTime() - f1.getTime())> 0 ? 1 : -1;
The 'FileSizeComparator' has the same issue but I think is less likely
to show unless really big files are in use.
I hope this helps.
Steve
Here is a short test class using Date instead of File, that shows the
problem:
package steve.test;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
public class ComparatorTest {
public static void main(String[] args) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date[] dateList = new Date[] {
sdf.parse("2002-01-01"),
sdf.parse("2002-01-02"),
sdf.parse("2002-01-03"),
sdf.parse("2002-01-04"),
sdf.parse("2002-02-05"),
sdf.parse("2002-03-06")
};
Arrays.sort(dateList, new DateComparator1());
System.out.println("sort error: " + Arrays.toString(dateList));
Arrays.sort(dateList, new DateComparator2());
System.out.println("sort fix: "+Arrays.toString(dateList));
} catch (Exception e) {
e.printStackTrace();
}
}
// reverse sort - latest come first
static private class DateComparator1 implements Comparator<Date> {
public int compare(Date f1, Date f2) {
System.out.print(f2+"-"+f1+" =
"+f2.getTime()+"-"+f1.getTime()+" = int: "+(int) (f2.getTime() -
f1.getTime()));
System.out.println(" long: "+(f2.getTime() - f1.getTime()));
return (int) (f2.getTime() - f1.getTime());
}
}
// reverse sort - latest come first
static private class DateComparator2 implements Comparator<Date> {
public int compare(Date f1, Date f2) {
return (f2.getTime() - f1.getTime())> 0 ? 1 : -1;
}
}
}
woah! thanks a lot, i hadnt seen that problem.
it also needs to return 0 when equal, eg:
// reverse sort - latest come first
static private class FileAgeComparator implements Comparator<File> {
public int compare(File f1, File f2) {
//return (int) (f2.lastModified() - f1.lastModified());
return (f1.lastModified()<f2.lastModified() ? 1 :
(f1.lastModified()==f2.lastModified() ? 0 : -1)); // Steve Ansari 6/3/2010
}
}
thanks again!