同步局部变量 [英] Synchronizing on local variable

查看:121
本文介绍了同步局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 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 ,在新创建的对象上没有争用的可能性,在其他方法中,在数组中找到的 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 Nodes 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆