这将尽可能接近目前的时间,没有重复.
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毫秒进行,直到时间赶上. 😉