加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – randomUUID是否提供唯一的ID?

发布时间:2020-12-14 16:36:51 所属栏目:Java 来源:网络整理
导读:我正在尝试为我的REST API创建会话令牌.每次用户登录时,我都创建了一个新的令牌 UUID token = UUID.randomUUID();user.setSessionId(token.toString());Sessions.INSTANCE.sessions.put(user.getName(),user.getSessionId()); 但是,我不知道如何防止重复的se
我正在尝试为我的REST API创建会话令牌.每次用户登录时,我都创建了一个新的令牌
UUID token = UUID.randomUUID();
user.setSessionId(token.toString());
Sessions.INSTANCE.sessions.put(user.getName(),user.getSessionId());

但是,我不知道如何防止重复的sessionTokens.

例如:当user1登录并获得令牌87955dc9-d2ca-4f79-b7c8-b0223a32532a和user2登录时,可能会出现一种情况,并且还会获得令牌87955dc9-d2ca-4f79-b7c8-b0223a32532a.

有更好的做法吗?

解决方法

如果您遇到UUID碰撞,请继续播放彩票.

维基百科:

Randomly generated UUIDs have 122 random bits. Out of a total of 128
bits,four bits are used for the version (‘Randomly generated UUID’),
and two bits for the variant (‘Leach-Salz’).

With random UUIDs,the
chance of two having the same value can be calculated using
probability theory (Birthday paradox). Using the approximation

p(n)approx 1-e^{-tfrac{n^2}{{2x}}}

these are the probabilities of an
accidental clash after calculating n UUIDs,with x=2122:

n probability
68,719,476,736 = 236 0.0000000000000004 (4 × 10?16)
2,199,023,255,552 = 241 0.0000000000004 (4 × 10?13)
70,368,744,177,664 = 246 0.0000000004 (4 × 10?10)

To put these numbers into perspective,the annual risk of someone being hit by a meteorite is estimated to be one chance in 17 billion,which means the probability is about 0.00000000006 (6 × 10?11),equivalent to the odds of creating a few tens of trillions of > UUIDs in a year and having one duplicate. 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%. The probability of one duplicate would be about 50% if every person on earth owns 600 million UUIDs.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读