Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How big is the chance to get a Java UUID.randomUUID collision? [duplicate]

Tags:

java

uuid

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;
    }
}
like image 583
daniels Avatar asked Jul 21 '14 22:07

daniels


People also ask

How likely is a UUID collision?

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.

Can random UUID be duplicate?

From the documentation and wikipedia we see that randomUUID is good - but there is a very small chance that duplicates can be generated.

What is the most reasonable way to handle the probability of UUID collision?

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.

Will UUIDs repeat?

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.


1 Answers

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.

like image 195
Óscar López Avatar answered Oct 16 '22 13:10

Óscar López