Yrl*_*lec 13 java concurrency timestamp throttling epoch
我需要在Java中创建一个时间戳(以毫秒为单位),该时间戳保证在该特定VM实例中是唯一的.我需要一些方法来限制System.currentTimeMillis()的吞吐量,这样它每ms最多返回一个结果.关于如何实现的任何想法?
Pet*_*rey 37
这将给出尽可能接近当前时间的时间而不重复.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
避免每毫秒限制一个id的一种方法是使用微秒时间戳.即将currentTimeMS乘以1000.这将允许每毫秒1000 ids.
注意:如果时间倒退,例如由于NTP校正,时间将在每次调用时以1毫秒的速度进行,直到时间赶上.;)
| 归档时间: |
|
| 查看次数: |
21447 次 |
| 最近记录: |