同步局部变量 [英] Synchronizing on local variable
问题描述
我注意到 ConcurrentHashMap
的计算
和 computeIfAbsent
方法:
I noticed a weird construct in ConcurrentHashMap
's compute
and computeIfAbsent
methods:
Node<K,V> r = new ReservationNode<K,V>();
synchronized (r) {
//...
}
考虑到JIT最有可能将其视为无操作,本地对象同步的重点是什么?
What is the point of synchronizing on a local object considering that the JIT will most likely treat it as a no-op?
推荐答案
在代码获取对象的监视器之后,对象的引用存储在选项卡
中,该选项卡是全局可见的节点数组,构成了 ConcurrentHashMap
:
Right after the code has acquired the object’s monitor, the reference to the object is stored into the tab
which is the globally visible array of nodes which make up the contents of the ConcurrentHashMap
:
Node<K,V> r = new ReservationNode<K,V>();
synchronized (r) {
if (casTabAt(tab, i, null, r)) {
此时,在同一个 ConcurrentHashMap
上执行其他修改方法的其他线程在遍历全局数组时可能会遇到此不完整的节点,换句话说, 节点
引用已转义。
Right at this point, other threads executing other modification methods on the same ConcurrentHashMap
might encounter this incomplete node while traversing the global array, in other words, the Node
reference has escaped.
当 ReservationNode $ c时已经构造了$ c>,在新创建的对象上没有争用的可能性,在其他方法中,在数组中找到的
Node
上进行同步,可能会准确地争论节点
。
While at the point where the ReservationNode
has been constructed, there is no possibility for contention on a newly created object, in the other methods, which are synchronizing on Node
s found in the array, there might be contention for exactly that Node
.
这就像是优先级同步。创建者在引用尚未转义的位置进行同步,因此保证在引用转义的点处成功,所有其他线程将不得不等待,在它们访问的不太可能(但仍然可能)的事件中正好节点
。
It’s like a "priority-synchronization". The creator is synchronizing at a point where the reference has not been escaped yet therefore it is guaranteed to succeed while at the point where the reference escapes, all other threads will have to wait, in the unlikely (but still possible) event that they access exactly that Node
.
这篇关于同步局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!