Can Instant.toEpochMilli() be used as a unique id?

1.4k Views Asked by At

I have to generate a unique Id which is readable as well hence cannot use UUID. So I thought of using Instant.toEpochMilli(). Can it be used as unique id?

3

There are 3 best solutions below

2
On BEST ANSWER

No. I personally faced with situation, when two objects had same id. I have tested System.nanoTime() and it looked OK, but in general case both variants are not correct.

Correct solutions:

  • UUID.randomUUID()
  • AtomicLong
  • Database sequence
0
On

Can it be used as unique id?

Only if you can be certain that you won't allocate two IDs within the same millisecond, which seems unlikely. A millisecond is a really brief time to a human being, but it isn't a brief time to a computer, not at all.

If you're doing this within a given runtime environment and don't have to have unique IDs between environments, just use an ever-increasing number instead (if it only needs to be within the running process, this can just be a static field somewhere you increment as necessary; across processes but in the same overall environment, a database sequence or similar; etc.). If it has to be unique between environments, you really do need to use a GUID or similar.

2
On

It generates the current time in millisecond. Well, in most cases, it is not good enough. Because if the timeout between 2 calls of this method is too short(ex: when you call it in the loop) it might be dupplicated. You may want to take a look at generating nanosecond(for example System.nanoTime()). To sum up, it's not encouraged to use millisec or even nano sec as unique id. But in some particular loose situations, it can be accepted.