有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多表单的java Id生成

谁能建议我使用下面的代码为我的文件生成id,它是否总是唯一的。 当100个表单同时自动创建表单时,它会在ID文本框中自动填充ID。因此,它应该是线程安全的,如果我重新启动应用程序,它永远不会重复应用程序停止之前已经生成的id

  private static final AtomicLong count = new AtomicLong(0L);  
    public static String generateIdforFile()  
    {
        String timeString = Long.toString(System.currentTimeMillis(), 36);
        String counterString = Long.toString(counter.incrementAndGet() % 1000, 36);
        return timeString + counterString;
    }

表单使用ClassName获取Id。generateIdforFile()


共 (2) 个答案

  1. # 1 楼答案

    为什么不直接使用UUID作为文件id呢?您可以使用以下内容:

    public static String generateIdforFile()  {
        return UUID.randomUUID().toString();
    }
    

    或者你需要一个(正在进行的)数值吗

    如果数字必须是数字(且不连续),则可以使用UUID#getLeastSignificantBits()UUID#getMostSignificantBits()作为数值

    引用this answer on SO

    So the most significant half of your UUID contains 58 bits of randomness, which means you on average need to generate 2^29 UUIDs to get a collision (compared to 2^61 for the full UUID).

    当然,您不会像使用完整UUID那样具有冲突安全性

  2. # 2 楼答案

    对于整个应用程序,最好使用从0L开始的全局AtomicLong。然后用CurrentTimeMillis连接

    static AtomicLong counter = new AtomicLong(0L);
    
    public static String generateIdforFile()  
    {
        String timeString = Long.toString(System.currentTimeMillis(), 36);
        String counterString = Long.toString(counter.incrementAndGet() % 1000, 36);
        return timeString + counterString;
    }
    

    即使在应用程序重启之间,这也有更大的机会生成唯一的ID,前提是你的应用程序关闭和重启所需的时间略多于几毫秒。请注意,该方法不再同步。(无需)而且前提是,您在同一毫秒内创建的文件少于1000个。但你不能保证普遍的独特性