Create a unique timestamp in Java

I need to create a timestamp (in milliseconds) in Java that is guaranteed to be unique in this particular VM instance That is, some methods are needed to suppress system The throughput of currenttimemillis() to return at most one result per Ms Any ideas on how to achieve it?

Solution

This will be as close to the current time as possible without repetition

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;
    }
}

One way to avoid limiting one ID per millisecond is to use microsecond timestamps Multiply currenttimems by 1000 This will allow 1000 IDS per second

Note: if the time is reversed, for example, due to NTP correction, the time will only be carried out for 1 millisecond per call until the time catches up

The above is all the contents of creating a unique timestamp in Java collected and sorted out by the programming house for you. I hope this article can help you solve the program development problems encountered in creating a unique timestamp in Java.

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>