Mac上的Java 8和FreeBSD不同的文件排序顺序由修改后的数据组成

kyb*_*org 0 java macos openjdk freebsd java-8

我面临着排序文件的奇怪问题.

鉴于环境

Dev: Mac OS X 10.11.3 OracleJDK 1.8.0_45
PreProduction env: FreeBSD 10 OpenJDK 1.8.0_72
Run Code Online (Sandbox Code Playgroud)

码

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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

给出一个输出

在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
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,运行应用程序的用户都具有对.git目录的读访问权.

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

P.J*_*sch 5

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

  • ...要避免此类错误,请改用"Comparator.comparingLong(File :: lastModified)".即使您必须手动比较`long`值,也只需使用`Long.compare(first,second)` (2认同)