Creating a unique timestamp in Java

后端 未结 5 1750
长情又很酷
长情又很酷 2021-02-02 00:20

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.cu

5条回答
  •  心在旅途
    2021-02-02 00:42

    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.

提交回复
热议问题