4

I am looking at a piece of code, and i can see that the following code has been written which generates a string, and that string has been set as the primary key of the table.

return new BigInteger(UUID.randomUUID().toString().replaceAll("-", ""), 16).toString(36);

Till now, there are lots of records and they seem to be unique as the primary key constraint is not violated.

I understand that the number will be random but will it be unique?

thanks

Tuco

Ratan Kumar
  • 1,640
  • 3
  • 25
  • 52
Tuco
  • 712
  • 2
  • 8
  • 20
  • Side question: since you are using a string as primary key anyway: why are you not using a UUID.randomUUID().toString()? That way other users of the database understand that the primary keys are UUIDs. – nd. Aug 29 '12 at 06:02
  • Quoting from wikipedia ( http://en.wikipedia.org/wiki/Universally_unique_identifier ) > In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. – MaVRoSCy Aug 29 '12 at 09:27
  • i forgot to mention that the code is already in place and is in production and is working fine till now. – Tuco Aug 29 '12 at 09:55

4 Answers4

4

There is no guarantee that the numbers will be unique, however it is extremely improbable that a duplicate will ever be generated because there is such a huge range.

The chance is extremely low even after considering the birthday paradox.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
1

The randomUUID function uses "a cryptographically strong pseudo random number generator" (from the Javadoc). This means that there is some math behind the random generation to minimize the risk of a collision (two numbers matching).

There is no 100% guarantee that the numbers will be entirely unique; however, there is an acceptably small chance that two numbers will match.

Kevin Lacquement
  • 5,057
  • 3
  • 25
  • 30
1

Quoting from Michael Borgwardt

UUID uses java.security.SecureRandom, which is supposed to be "cryptographically strong". While the actual implementation is not specified and can vary between JVMs (meaning that any concrete statements made are valid only for one specific JVM), it does mandate that the output must pass a statistical random number generator test.

You can also read how good is java's UUID.randomUUID? and How unique is UUID? for more info

Community
  • 1
  • 1
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
0

UUID are actually universally unique identifiers.Some of its usage are for creating random file names, session id in web application, transaction id and for record's primary keys in database replacing the sequence or auto generated number.

Mohammod Hossain
  • 4,134
  • 2
  • 26
  • 37