简体   繁体   English

Java ConcurrentHashMap实现

[英]Java ConcurrentHashMap implementation

I was just looking at the source code of Java's ConcurrentHashMap and found this line of code: 我只是看了Java的ConcurrentHashMap的源代码,发现了这行代码:

/*
 * The maximum number of times to tryLock in a prescan before possibly blocking on acquire in   
 * preparation for a locked segment operation. On multiprocessors, using a bounded number of  
 * retries maintains cache acquired while locating nodes.
 */
static final int MAX_SCAN_RETRIES =
              Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1

The MAX_SCAN_RETRIES is used in looking up entries while acquiring lock. MAX_SCAN_RETRIES用于在获取锁定时查找条目。 My question is how is the number 64 determined for a multi-processor machine? 我的问题是如何确定多处理器机器的数字64 Anybody know the theory behind the number 64 ? 有人知道64号背后的理论吗?

When dealing with lock retries across multiple CPUs there is a balance that you strike between attempting to get the lock quickly (spinning) and allowing the CPU to switch to another thread to avoid wasting CPU time spinning on the lock that isn't going to be released soon. 在处理多个CPU的锁定重试时,在尝试快速获取锁定(旋转)和允许CPU切换到另一个线程以避免浪费CPU时间旋转到不会出现的锁定之间存在平衡。即将发布。 The actual number of spins allowed for a CPU to attempt to obtain a lock is strongly affected by both the actual speed of the overall system as well as by the amount of code that typically executes within the critical section. CPU尝试获取锁定所允许的实际旋转次数受整个系统的实际速度以及通常在关键部分内执行的代码量的影响很大。

This issue has deep roots in the Stopping Problem and many other issues related to OS design on SMP systems with respect to optimizing concurrency. 此问题深深扎根于停止问题以及与SMP系统上的OS设计相关的许多其他与优化并发性相关的问题。 This kind of design choice is typically resolved via a trial and error approach across many applications; 这种设计选择通常通过许多应用程序的试错法解决; however the choice of 64 looks to me like an arbitrary call on the part of the implementer (the number is a power of two). 然而64的选择在我看来就像是实施者的任意调用(数字是2的幂)。

Unfortunately this particular code is both buggy and limiting. 不幸的是,这个特殊的代码既有缺陷也有限制。 Buggy in that the documentation for availableProcessors states "This value may change during a particular invocation of the virtual machine," hence potentially causing the lock to spin too many times (should the count move from > 1 to = 1) or too few (in the visa-versa case). Buggy,因为availableProcessors的文档声明“此值可能会在特定的虚拟机调用期间发生变化”,因此可能会导致锁定旋转太多次(如果计数从> 1移动到= 1)或太少(在反之亦然的情况)。 It is limiting in that a developer that really needs to tune concurrency in their application has no ability to do so as MAX_SCAN_RETRIES is final (though some tricks may be played with reflection). 它的局限性在于,真正需要在其应用程序中调整并发性的开发人员无法这样做,因为MAX_SCAN_RETRIES是最终的(尽管一些技巧可以用反射来播放)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM