Java 8 在 Mac 和 FreeBSD 上不同 文件按修改后的数据排序

Java 8 on Mac and FreeBSD different File sorting order by modified data

我在排序文件时遇到了奇怪的问题。

给定环境

Dev: Mac OS X 10.11.3 OracleJDK 1.8.0_45
PreProduction env: FreeBSD 10 OpenJDK 1.8.0_72

代码

public static String getLatestTag() {
    File tagsDir = new File("./.git/refs/tags");
    ...
    File[] tags = tagsDir.listFiles();
    List<File> tagsList = Arrays.asList(tags);
    Collections.sort(tagsList, (f1, f2) -> {
       if(f1.lastModified() > f1.lastModified()) {
          return 1;
       } else if(f1.lastModified() == f2.lastModified()) {
          return 0;
       } else {
          return -1;
       }
     });
     logTagsList(tagsList);
     String latestTag = tagsList.get(0).getName();
     Logger.info("Application version is: %s", latestTag.replaceAll("[^\d.]", ""));
     return latestTag;
}

private static void logTagsList(List<File> tags) {
    if(Logger.isDebugEnabled()) {
        Logger.debug("Tags found");
        for(File tag : tags) {
            Logger.debug("Tag: %s, Date modified: %s", tag.getName(), tag.lastModified());
        }
    }
}

给出输出

在Mac:

17:49:50,601 DEBUG ~ Tags found
17:49:50,602 DEBUG ~ Tag: v0.97, Date modified: 1457277455000
17:49:50,602 DEBUG ~ Tag: v0.95, Date modified: 1455809758000
17:49:50,602 INFO  ~ Application version is: 0.97

在 FreeBSD 上:

18:52:49,902 DEBUG ~ Tags found
18:52:49,903 DEBUG ~ Tag: v0.95, Date modified: 1456038720000
18:52:49,903 DEBUG ~ Tag: v0.97, Date modified: 1457277515000
18:52:49,904 INFO  ~ Application version is: 0.95

在这两种情况下,运行正在使用应用程序的用户都具有对 .git 目录的读取权限。

重现步骤: 1) git 初始化 2) bootstrap java 应用(或play framework 1.4 应用完整重现) 3)添加给定的代码 4) 对 git 进行 2 次提交 5)标记那些提交 6) 运行 申请 7) 检查日志

您在比较时遇到错误:if(f1.lastModified() > f1.lastModified()) - 您在此处将 f1 与 f1 进行比较。如果两个文件没有同时修改,无论你比较什么,你总是返回 -1。这会导致不可预测的行为。