unique Number generation by UUID in Java ?

爱⌒轻易说出口 提交于 2019-12-22 10:04:52

问题


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


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/12171558/unique-number-generation-by-uuid-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!