- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
这个问题是关于 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/
我有这种来自 Google map 自动完成的奇怪行为(或者我可能错过了某事)...想法?奇怪的: 您在输入中输入某物,例如“伦敦” 您按 [ENTER] 你按下 [CLEAR] 按钮 你点击进入'输
这段代码与《Learning Java》(Oracle Press Books)一书中的代码完全一样,但它不起作用。我不明白为什么它不起作用,它应该起作用。我用 OpenJDK 和 Sun JDK 7
示例 1 中究竟发生了什么?这是如何解析的? # doesnt split on , [String]::Join(",",("aaaaa,aaaaa,aaaaa,aaaaa,aaaaa,aa
我需要获得方程式系统的解决方案。为此,我使用函数sgesv_()。 一切都很好,它使我感到解决方案的正确结果。 但是我得到一个奇怪的警告。 警告:从不兼容的指针类型传递'sgesv_'的参数3 我正在
我目前在制作动画时遇到一个奇怪的问题: [UIView animateWithDuration:3 delay:0
alert('works'); $(window).load(function () { alert('does not work'); });
我的代码: public class MyTest { public class StringSorter implements Comparator { public
我正在学习 JavaScript。尝试理解代码, function foo (){ var a = b = {name: 'Hai'}; document.write(a.name +''
这个问题不太可能帮助任何 future 的访问者;它只与一个小的地理区域、一个特定的时间点或一个非常狭窄的情况有关,这些情况并不普遍适用于互联网的全局受众。为了帮助使这个问题更广泛地适用,visit
这按预期工作: [dgorur@ted ~]$ env -i env [dgorur@ted ~]$ 这样做: [dgorur@ted ~]$ env -i which date which: no
struct BLA { int size_; int size()const{ return size_; } } int x; BLA b[ 2 ]; BLA * p = &b[
我有以下代码: #test img {vertical-align: middle;} div#test { border: 1px solid green; height: 150px; li
我想大多数使用过 C/C++ 的人都对预处理器的工作原理有一定的直觉(或多或少)。直到今天我也是这么认为的,但事实证明我的直觉是错误的。故事是这样的: 今天我尝试了一些东西,但我无法解释结果。首先考虑
我想为 TnSettings 做 mock,是的,如果通过以下方法编写代码,它就可以工作,问题是我们需要为每个案例编写 mock 代码,如果我们只 mock 一次然后执行多个案例,那么第二个将报告异常
我的项目中有以下两个结构 typedef volatile struct { unsigned char rx_buf[MAX_UART_BUF]; //Input buffer over U
Regex rx = new Regex(@"[+-]"); string[] substrings = rx.Split(expression); expression = "-9a3dcb
我的两个应用程序遇到了一个奇怪的问题。这是设置: 两个 tomcat/java 应用程序,在同一个网络中运行,连接到相同的 MS-SQL-Server。一个应用程序,恰好按顺序位于 DMZ 中可从互联
我目前正在与 Android Api Lvl 8 上的 OnLongClickListener 作斗争。 拿这段代码: this.webView.setOnLongClickListener(new
这个问题不太可能帮助任何 future 的访问者;它只与一个小的地理区域、一个特定的时间点或一个非常狭窄的情况相关,这些情况并不普遍适用于互联网的全局受众。为了帮助使这个问题更广泛地适用,visit
只是遇到了奇怪的事情。我有以下代码: -(void)ImageDownloadCompleat { [self performSelectorOnMainThread:@selector(up
我是一名优秀的程序员,十分优秀!