-2

everyone.

I have a simple question. Is the value returned by UUID.randomUUID().getMostSignificantBits() ALWAYS unique?

I need to generate a Long value which needs to ALWAYS be unique. Is there any other way to generate a Long that accomplishes this?

Thanks.

Angel D.
  • 162
  • 2
  • 11
  • 1
    `return counter++`? Of course you can't expect more than 2^64 unique long values. – JB Nizet Jul 03 '19 at 16:37
  • 1
    `Yes, it is theoretically possible for the UUID.randomUUID method to return a duplicate, but this is not at all a realistic concern. The Oracle/OpenJDK implementation uses a cryptographically-strong random number generator. Given that, and given the astronomical range given by so many bits in a UUID, you can generate many millions of such values in your app and still sleep well. Using one of the other variants further reduces the possibility of collisions even closer to zero because of using "space and time", [1] MAC address or name, and [2] current date-time, as constraints.` – Yassin Hajaj Jul 03 '19 at 16:38
  • @YassinHajaj that's true for a full UUID, but not for a truncated one. Even with a perfect 64-bit random number generator you'd expect to see a duplicate after generating ~2^32 numbers, due to the birthday paradox. – MikeFHay Jul 03 '19 at 16:55
  • Also, this question is clearly not a duplicate of the one it's been closed as a duplicate of. – MikeFHay Jul 03 '19 at 16:58
  • @MikeFHay vote for reopen if you feel like it should be reopened. But it seems clear to me that it is a duplicate, as it answers the first question. 2nd question : is there another way, probably not. – Yassin Hajaj Jul 03 '19 at 17:16
  • @YassinHajaj "probably not"? That depends on the details of OP's requirements. JB Nizet and orirab already suggested possible solutions. Why deny them the opportunity to help OP? – MikeFHay Jul 03 '19 at 17:28
  • @MikeFHay is right. The implementation should be depended on OP's requirements. "True Unique" is a fake requirement. – shawn Jul 04 '19 at 02:41

1 Answers1

0

No, it's impossible to be always unique. If you loop about max(long)+1 times to generate values, you must get at least one duplicated value.

The implementation should be depended on OP's requirements. "True Unique" is a fake requirement.

shawn
  • 4,305
  • 1
  • 17
  • 25