The get method of ConcurrentHashMap is eventually consistent

Prove that
thread 1 calls get at time point A, and then thread 2 calls get again at a time point B. Before the two methods return, call the put method, overwriting the data just now and considering this execution sequence.

1. 线程2读到数据,然后时间片用完
2. put成功将数据覆盖 
3. 线程1读到新数据,返回
4.线程2拿到时间片,返回旧数据

The result is that thread 1 returns to get the new data first, and thread 2 returns to get the old data.

Description

As mentioned in the comments of ConcurrentHashMap, the get method can only guarantee to see the operations completed before, and cannot guarantee to see the operations in progress.

For the concurrentHashMap of jdk1.7, the get method is very good.
A simple summary of the get method without locking:

1. 访问的绝大数变量是volatile类型的,如count,node.val,node.next
2. 访问的变量只有一个不是volatile的,即table[]得每个元素,也就是说可能刚才已经成功插入一个table[i]
   =node,但是读的时候确是null
3. 当找不到的时候,它会在加锁的情况下再读一次   

Guess you like

Origin blog.csdn.net/qq_41634872/article/details/110246465