Is unique id generation using UUID really unique?

后端 未结 3 762
终归单人心
终归单人心 2020-12-20 14:05

I want generate unique ID just like auto increment in java . So previously i used current nano seconds but i end up with clash since two data comes with in same nano second

3条回答
  •  萌比男神i
    2020-12-20 14:57

    I seriously doubt you get two records in the same nano-second as making the call System.nanoTime() takes over 100 ns. It is more likely your clock doesn't have nano second accuracy.

    However, if you restart your server, you can get repeating nanoTime().

    One way around this is to use

    AtomicLong counter = new AtomicLong(System.currentTimeMillis()*1000);
    
    long id = counter.incrementAndGet();
    
    // something like ctz9yamgu8
    String id = Long.toString(counter.incrementAndGet(), 36);
    

    This will start a counter when the application restarts and they will not be overlap between restarts unless you sustain over one million ids per second. (Over the life of the instance)

    Note: this only works for on a per instance basis. Multiple servers need to use a different approach.

提交回复
热议问题