Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a unique timestamp in Java

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?

like image 488
Yrlec Avatar asked Feb 08 '12 10:02

Yrlec


People also ask

How do I create a unique timestamp?

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.

Is timestamp unique in Java?

* Timestamps are unique across threads/processes on a single machine.

Can timestamps be unique?

timestamp is a data type that exposes automatically generated binary numbers, which are guaranteed to be unique within a database.

How do you create a timestamp in Java?

A Timestamp also provides formatting and parsing operations to support the JDBC escape syntax for timestamp values. The precision of a Timestamp object is calculated to be either: 19 , which is the number of characters in yyyy-mm-dd hh:mm:ss. 20 + s , which is the number of characters in the yyyy-mm-dd hh:mm:ss.


2 Answers

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

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.

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. ;)

like image 137
Peter Lawrey Avatar answered Sep 22 '22 10:09

Peter Lawrey


You can use System.nanoTime() for better accuracy

Although I tried below and each time it gives different values, it probably is not guaranteed to be unique all the time.

public static void main(String[] args) {
        long time1 = System.nanoTime();
        long time2 = System.nanoTime();
        long time3 = System.nanoTime();
        System.out.println(time1);
        System.out.println(time2);
        System.out.println(time3);
    }

Another way is to use AtomicInteger/AtomicLong classes for unique numbers if the time is not important for you and you just need unique number, this probably is a btter choice.

like image 41
fmucar Avatar answered Sep 24 '22 10:09

fmucar