Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example Analysis of the principle of size method in concurrenthashmap

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

The editor will share with you an example analysis of the principle of the size method in concurrenthashmap. I hope you will get something after reading this article. Let's discuss it together.

The principle of size method of concurrenthashmap

Ditto, this was also asked during the same interview. I just remember seeing that it would be counted many times in concurrenthashmap. At that time, it was said that it would be counted twice for comparison, and people then asked why. I was silly for a moment, isn't it obvious that there are new changes in the middle of the two statistics, which will lead to statistical inaccuracy? At that time, I didn't know what to say. I thought he had a new point, so I said I didn't know. During the interview, many questions actually calm down and think about it, which can be taken a step further, sometimes because they are afraid that he will dig a bigger hole after he goes further.

Let's talk about this size method in detail.

The code will not be posted. Just the principle.

As we all know, concurrenthashmap has a lot of songs segments. First, iterate through segments and add up the count of each segment as the size of the entire concurrenthashMap. If there is no concurrency, this is fine, but it is multithreaded. If there is a change in the front foot and the back foot, it is not accurate. ModCount and two comparisons are introduced in the source code to achieve size confirmation. The specific process is as follows:

1. Traverse the segments array for the first time

The count of each segemnt is added as the total, and the modCount of each segment is added to sum as the basis for judging whether the result has been modified or not.

Here we need to mention modCount, which is an incremental operation when segment has any operation, which represents the number of operations that affect the number of elements in the Segment. This value only increases, not decreases! It is important to increase rather than decrease, so that one segment+1 does not appear, resulting in modcount+1, and another segment-1, modcount-1, so that the modcount does not change when counting all.

The 2.size operation traverses all the Segments twice.

Record the modcount value of Segment each time, and then compare the modCount twice. If it is the same, it means that no write operation has occurred during the period, and the result of the original traversal will be returned. If it is not the same, the process will be repeated again. If it is not the same again, you will need to lock all the Segment, and then traverse one by one.

3. If, after judgment, it is found that the two statistics of modCount are not consistent.

As mentioned above, it is necessary to re-enable all segment locking methods for count acquisition and statistics, so that during this period, each segement is locked and cannot perform other operations, and the statistical count is naturally very accurate.

The reason why we have to judge without locking first is that we do not want to acquire so many locks because of the size operation, because acquiring locks not only takes up resources, but also affects the use of ConcurrentHash by other threads and the efficiency of program execution in concurrent cases. Be careful when using locks!

The principle is probably like this, the specific code can look at the source code, and the source code 1.7 and 1.8 are different. Let's post it sometime and compare it.

Thoughts on size of concurrenthashmap

ConcurrentHashMap controls the security and concurrency of the whole Map through segmented locking, so how does ConcurrentHashMap strike a balance between performance and security when seeking size?

We will first think of the following two ways

1. Get all Segment locks.

This approach is feasible, but it can lead to poor concurrency performance, because you have acquired all the locks, so other threads will not be able to do anything on the HashMap.

two。 Get the Segment one by one.

There is also a problem with this method, it is possible to get the number of elements in the next Segment later, the number of elements in the above Segment is likely to change, so in the end, the data may be wrong.

So what measures are taken by ConcurrentHashMap? The source code is as follows:

Previous source code of java1.7:

Since the probability of changes in the accumulated count in the process of accumulating count is very small, ConcurrentHashMap first tries to calculate the size of each Segment by unlocking the Segment twice. If the count of the Segment changes in the statistical process, then lock the count of the statistical Segment.

Java1.7 and the source code after 1Jing 7:

The core of taking size is the sumCount function.

Final long sumCount () {CounterCell [] as = counterCells; CounterCell a; long sum = baseCount; if (as! = null) {for (int I = 0; I < as.length; + + I) {if ((a = as [I])! = null) sum + = a.value;}} return sum;}

Core logic: when counterCells is not null, iterate through the elements and accumulate with baseCount.

Look at two properties: baseCount and counterCells.

Take a look at baseCount first.

Private transient volatile long baseCount

BaseCount is a variable of volatile, which is used in the addCount method, while the addCount method is called after the put ends. In the addCount method, CAS addition is done to this variable.

Private final void addCount (long x, int check) {CounterCell [] as; long b, s; if ((as = counterCells)! = null |! U.compareAndSetLong (this, BASECOUNT, b = baseCount, s = b + x)) {CounterCell a; long v; int m; boolean uncontended = true If (as = = null | | (m = as.length-1) < 0 | | (a = as [ThreadLocalRandom.getProbe () & m]) = = null | |! (uncontended = U.compareAndSetLong (a, CELLVALUE, v = a.value, v + x)) {fullAddCount (x, uncontended); return } if (check

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report