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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
While searching for a solution I came across ULIB (Universally Unique Lexicographically Sortable Identifier) https://github.com/huxi/sulky/tree/master/sulky-ulid/
It's not a long, but shorter then UUID.
A ULID:
You could use
System.nanoTime()
, which is the most precise available system timer, and divide that by million to get milliseconds. While there are no formal guarantees on how often it's updated, I believe it's reasonable to assume that it updates way more (order(s) of magnitude) frequently than once per millisecond. Of course, if you create integer timestamps by less than millisecond interval, then they can't all be unique.Note that the absolute value
nanoTime()
is arbitrary. If you want absolute time, calibrate it somehow, i.e. compare it tocurrentTimeMillis()
when starting.This will give a time as close the current time as possible without duplicates.
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. ;)
You can use
System.nanoTime()
for better accuracyAlthough I tried below and each time it gives different values, it probably is not guaranteed to be unique all the time.
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.Could you perhaps make use of
java.util.UUID
and it'stimestamp()
andclockSequence()
?More details here: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/UUID.html