在Java中创建唯一的时间戳

在Java中创建唯一的时间戳

本文介绍了在Java中创建唯一的时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Java中创建一个时间戳(以毫秒为单位),该时间戳在该特定VM实例中保证是唯一的。也就是说需要一些方法来扼制System.currentTimeMillis()的吞吐量,以便每ms最多返回一个结果。

I need to create a timestamp (in milliseconds) in Java that is guaranteed to be unique in that particular VM-instance. I.e. need some way to throttle the throughput of System.currentTimeMillis() so that it returns at most one results every ms. Any ideas on how to implement that?

推荐答案

这将给出一个尽可能接近当前时间,没有重复的时间。 p>

This will give a time as close the current time as possible without duplicates.

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。

One way to avoid the limitation of one id per milli-second is to use a micro-second timestamp. i.e. multiply currentTimeMS by 1000. This will allow 1000 ids per milli-second.

注意:如果时间向后,例如由于NTP校正,每次调用1毫秒,直到时间赶上。 ;)

Note: if time goes backwards, eg due to an NTP correction, the time will just progress at 1 milli-second per invocation until time catches up. ;)

这篇关于在Java中创建唯一的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 15:43