在Java中创建唯一的时间戳

2024-01-04

我需要在 Java 中创建一个时间戳(以毫秒为单位),并保证在该特定 VM 实例中是唯一的。 IE。需要某种方法来限制 System.currentTimeMillis() 的吞吐量,以便它每毫秒最多返回一个结果。关于如何实现它有什么想法吗?


这将给出尽可能接近当前时间且不重复的时间。

private static final AtomicLong LAST_TIME_MS = new AtomicLong();
public static long uniqueCurrentTimeMS() {
    long now = System.currentTimeMillis();
    while(true) {
        long lastTime = LAST_TIME_MS.get();
        if (lastTime >= now)
            now = lastTime+1;
        if (LAST_TIME_MS.compareAndSet(lastTime, now))
            return now;
    }
}

避免每毫秒一个 id 限制的一种方法是使用微秒时间戳。即,将 currentTimeMS 乘以 1000。这将允许每毫秒 1000 个 id。

注意:如果时间倒退,例如由于 NTP 校正,时间将仅以每次调用 1 毫秒的速度前进,直到时间赶上。 ;)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Java中创建唯一的时间戳 的相关文章

随机推荐