java.util.UUID 线程安全吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7212635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:05:53  来源:igfitidea点击:

is java.util.UUID thread safe?

javamultithreadingthread-safety

提问by Abhishek Gayakwad

I am asking this question because of following observations

我问这个问题是因为以下观察

  1. getting this stack trace in thread dump in highly multi threaded environment

    "http-80-200" daemon prio=10 tid=0x00002aaab4981000 nid=0x7520 waiting \
     for monitor entry [0x000000004fec7000]
       java.lang.Thread.State: BLOCKED (on object monitor)
        at java.security.SecureRandom.nextBytes(SecureRandom.java:433)
        - waiting to lock <0x00000000c00da220> (a java.security.SecureRandom)
        at java.util.UUID.randomUUID(UUID.java:162)
    
  2. found this link

    http://bugs.sun.com/view_bug.do?bug_id=6611830

  1. 在高度多线程环境中的线程转储中获取此堆栈跟踪

    "http-80-200" daemon prio=10 tid=0x00002aaab4981000 nid=0x7520 waiting \
     for monitor entry [0x000000004fec7000]
       java.lang.Thread.State: BLOCKED (on object monitor)
        at java.security.SecureRandom.nextBytes(SecureRandom.java:433)
        - waiting to lock <0x00000000c00da220> (a java.security.SecureRandom)
        at java.util.UUID.randomUUID(UUID.java:162)
    
  2. 找到这个链接

    http://bugs.sun.com/view_bug.do?bug_id=6611830

if UUID is not thread safe, please suggest any other library if it exist.

如果 UUID 不是线程安全的,请建议任何其他库(如果存在)。

回答by Joonas Pulakka

UUID is immutable so it's potentially thread safe, but apparently there was some evil caching going onin some accessors that made it unsafe (that bug is fixed now).

UUID 是不可变的,因此它可能是线程安全的,但显然在某些访问器中进行了一些邪恶的缓存,使其不安全(该错误现已修复)。

But your thread dump just says that a thread is waiting for a lock at SecureRandom.nextBytes, which is used by the UUID.randomUUIDfactory, which definitely isthread-safe. It's what's supposed to happen when several threads call it simultaneously, as far as I can tell.

但是您的线程转储只是说一个线程正在等待工厂SecureRandom.nextBytes使用的锁UUID.randomUUID,这绝对线程安全的。据我所知,这是当多个线程同时调用它时应该发生的事情。

回答by Number945

Uuid is thread safe however there is another library called JUGwhich is more efficient in performance.

Uuid 是线程安全的,但是还有另一个名为JUG 的库 ,它的性能更高效。

Source :http://www.dcalabresi.com/blog/java/generate-java-uuid-performance/

来源:http: //www.dcalabresi.com/blog/java/generate-java-uuid-performance/