这个问题是关于 ThreadLocalRandom
在 OpenJDK 1.8.0 版本中的实现。
ThreadLocalRandom
提供了一个每线程随机数生成器,没有 Random 强加的同步开销。最明显的实现 (IMO) 应该是这样的,它似乎可以保持向后兼容性而不会太复杂:
public class ThreadLocalRandom extends Random {
private static final ThreadLocal<ThreadLocalRandom> tl =
ThreadLocal.withInitial(ThreadLocalRandom::new);
public static ThreadLocalRandom current() {
return tl.get();
}
// Random methods moved here without synchronization
// stream methods here
}
public class Random {
private ThreadLocalRandom delegate = new ThreadLocalRandom();
// methods synchronize and delegate for backward compatibility
}
然而,实际的实现是完全不同的,而且非常奇怪:
ThreadLocalRandom
逐字复制了Random
中的一些方法,其他方法稍作修改;肯定可以重复使用大部分代码。Thread
存储用于初始化`ThreadLocalRandom 的种子和探测变量,违反封装;ThreadLocalRandom
使用Unsafe
访问Thread
中的变量,我想这是因为这两个类在不同的包中但状态变量在Thread
中必须是私有(private)的 -Unsafe
是必需的,因为封装违规;ThreadLocalRandom
将其下一个nextGaussian
存储在静态ThreadLocal
中,而不是像Random
那样存储在实例变量中。
总的来说,我的粗略检查似乎揭示了一个丑陋的 Random
副本,与上面的简单实现相比没有任何优势。但是标准库的作者很聪明,所以这种奇怪的方法肯定有一些的原因。有谁知道为什么 ThreadLocalRandom
是以这种方式实现的?
最佳答案
关键问题是很多代码都是遗留的,不能(轻易)更改 - Random
通过同步其所有方法被设计为“线程安全”。这在 Random
的实例中有效可以跨多个线程使用,但这是一个严重的瓶颈,因为没有两个线程可以同时检索随机数据。一个简单的解决方案是构造一个 ThreadLocal<Random>
对象从而避免了锁争用,但这仍然不理想。 synchronized
仍有一些开销方法,即使在无争议的情况下,构建n Random
当它们基本上都在做同样的工作时,实例是浪费的。
所以在高层次上 ThreadLocalRandom
作为性能优化存在,因此它的实现将是“奇怪的”是有道理的,因为 JDK 开发人员已经花时间对其进行优化。
JDK中有很多类,乍一看,“丑陋”。但是请记住,JDK 作者正在解决与您不同的问题。他们编写的代码将以无数方式被成千上万甚至数百万的开发人员使用。他们必须定期权衡最佳实践以提高效率,因为他们编写的代码非常关键。
Effective Java: Item 55还解决了这个问题——关键是优化应该作为最后的手段,由专家来完成。 JDK 开发人员就是那些专家。
针对您的具体问题:
ThreadLocalRandom
duplicates some of the methods inRandom
verbatim and others with minor modifications; surely much of this code could have been reused.
很遗憾,没有,因为 Random
上的方法是 synchronized
.如果它们被调用 ThreadLocalRandom
会拉进来 Random
的锁争用问题。 TLR 需要 重写每个方法以删除 synchronized
来自方法的关键字。
Thread
stores the seed and a probe variable used to initialize theThreadLocalRandom
, violating encapsulation;
首先,它真的不是“违反封装”,因为该字段仍然是包私有(private)的。它是从用户那里封装的,这是目标。我不会太在意这个,因为这里做出的决定是为了提高性能。有时性能是以正常的良好设计为代价的。实际上,这种“违规”是检测不到的。该行为被简单地封装在两个类中,而不是一个单独的类中。
将种子放入 Thread
允许 ThreadLocalRandom
完全无状态(除了 initialized
字段,这在很大程度上是无关紧要的),因此整个应用程序只需要存在一个实例。
ThreadLocalRandom
usesUnsafe
to access the variables inThread
, which I suppose is because the two classes are in different packages yet the state variables must be private inThread
-Unsafe
is only necessary because of the encapsulation violation;
许多 JDK 类使用 Unsafe
.这是一种工具,而不是一种罪恶。同样,我只是不会因为这个事实而感到压力太大。该类称为 Unsafe
以阻止外行开发人员滥用它。我们相信/希望 JDK 作者足够聪明,知道什么时候可以安全使用。
ThreadLocalRandom
stores its nextnextGaussian
in a staticThreadLocal
instead of in an instance variable asRandom
does.
因为永远只有一个 ThreadLocalRandom
的实例没有必要将它作为实例变量。我想你也可以证明它没有必要成为 static
。要么,但那时你只是在争论风格。至少要做到 static
更清楚地使该类基本上无状态。作为mentioned在文件中,这个字段并不是真正必要的,但确保与 Random
类似的行为.
关于java - 为什么 ThreadLocalRandom 的实现如此奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40620026/