为什么 ThreadLocalRandom 的实现如此奇怪?

Why is ThreadLocalRandom implemented so bizarrely?

这个问题是关于 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
}

然而,实际的实现完全不同而且很奇怪:

总的来说,我的粗略检查似乎揭示了一个丑陋的 Random 副本,与上面的简单实现相比没有任何优势。但是标准库的作者很聪明,所以这种奇怪的方法肯定有 一些 的原因。有谁知道为什么 ThreadLocalRandom 是以这种方式实施的?

关键问题是很多代码都是遗留的,不能(轻易)更改 - Random 被设计为 "thread-safe" 通过同步其所有方法。这是可行的,因为 Random 的实例可以跨多个线程使用,但这是一个严重的瓶颈,因为没有两个线程可以同时检索随机数据。一个简单的解决方案是构造一个 ThreadLocal<Random> 对象从而避免锁争用,但这仍然不理想。即使没有争议,一些 方法仍然有 synchronized 开销,并且构建 n Random 实例是浪费的基本上都在做同样的工作。

所以在 high-level ThreadLocalRandom 作为性能优化存在,因此它的实现是 "bizarre" 是有道理的,因为 JDK 开发人员已经投入时间对其进行优化。

JDK里面有很多class,乍一看是"ugly"。但是请记住,JDK 作者正在解决与您不同的问题。他们编写的代码将以无数方式被成千上万甚至数百万的开发人员使用。他们必须定期 trade-off best-practices 以提高效率,因为他们编写的代码非常关键。

Effective Java: Item 55 也解决了这个问题——关键是优化应该作为最后的手段,由专家来完成。 JDK 开发人员 专家。

针对您的具体问题:

ThreadLocalRandom duplicates some of the methods in Random verbatim and others with minor modifications; surely much of this code could have been reused.

很遗憾,没有,因为 Random 上的方法是 synchronized。如果它们被调用,ThreadLocalRandom 会带来 Random 的 lock-contention 麻烦。 TLR 需要 覆盖每个方法,以便从方法中删除 synchronized 关键字。

Thread stores the seed and a probe variable used to initialize the ThreadLocalRandom, violating encapsulation;

首先,它确实不是 "violating encapsulation",因为字段仍然是 package-private。它是从用户那里封装的,这是目标。我不会太在意这个,因为这里做出的决定是为了提高性能。有时性能是以正常的良好设计为代价的。在实践中,这个 "violation" 是检测不到的。该行为简单地封装在两个 class 中,而不是一个。

将种子放入 Thread 允许 ThreadLocalRandom 完全无状态(除了 initialized 字段,这在很大程度上是不相关的),因此只需要一个实例存在于整个应用程序中。

ThreadLocalRandom uses Unsafe to access the variables in Thread, which I suppose is because the two classes are in different packages yet the state variables must be private in Thread - Unsafe is only necessary because of the encapsulation violation;

许多 JDK class 使用 Unsafe。这是一种工具,而不是一种罪恶。同样,我只是不会因为这个事实而感到压力太大。 class 被称为 Unsafe 以防止 lay-developers 滥用它。我们 trust/hope JDK 作者足够聪明,知道什么时候可以安全使用。

ThreadLocalRandom stores its next nextGaussian in a static ThreadLocal instead of in an instance variable as Random does.

因为 ThreadLocalRandom 只有一个实例,所以没有必要将它作为实例变量。我想你也可以证明它也不需要成为 static ,但那时你只是在争论风格。至少让它 static 更清楚地离开 class 本质上是无状态的。作为文件中的 mentioned,该字段并不是真正必需的,但确保与 Random.

类似的行为