I need to create some uniques files in Java and i plan to use UUID.randomUUID to generate their names. Is there any chance to get a collision for this? Should i do something like bellow os I shouldn't worry about this?
Integer attemptsToGenerateUUID = 1;
while (true) {
UUID fileUUID = UUID.randomUUID();
if (fileDoesNotExistwith this UUID name) {
save file;
break;
}
attemptsToGenerateUUID += 1;
if (attemptsToGenerateUUID > 64) {
return false;
}
}
A collision is possible but the total number of unique keys generated is so large that the possibility of a collision is almost zero. As per Wikipedia, the number of UUIDs generated to have atleast 1 collision is 2.71 quintillion. This is equivalent to generating around 1 billion UUIDs per second for about 85 years.
From the documentation and wikipedia we see that randomUUID is good - but there is a very small chance that duplicates can be generated.
However, I would believe that writing code for generating a new UUID in the case of a collision and trying again to be a waste of time. The chance of a collision occurring is so small that throwing an exception would be a perfectly reasonable way of dealing with it.
A sample of 3.26*10¹⁶ UUIDs has a 99.99% chance of not having any duplicates. Generating that many UUIDs, at a rate of one per second, would take a billion years.
According to wikipedia, regarding the probability of duplicates in random UUIDs:
Only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. Or, to put it another way, the probability of one duplicate would be about 50% if every person on earth owned 600 million UUIDs.
I guess the same reasoning applies to Java's implementation of UUID. So no, you should not worry about this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With