简体   繁体   中英

What does segmentMask mean in java ConcurrentHashMap

I think that

(hash >>> segmentShift) & segmentMask

equals

(hash >>> segmentShift)

for example, ssize is 16, sshift is 4, so segmentShift is 28, segmentMask is 15

hash >>> segmentShift

will get high 4 bit, when do & operation with segmentMask, nothing gets changed.

What's the point I am misunderstanding?

Well, What I understand from here is that this whole operation

(hash >>> segmentShift) & segmentMask

is used for finding the location of segment in table. As you already mentioned that (hash >>> segmentShift) is used for getting the top 4 bit of key's hash.

but main job of segment mask is to equally distribute the segment in segment tables array. There are many segments in ConcurrentHashMap so to avoid collision, this segment mask is used. And segment mask is [(power of 2)-1].

This concept is similar like HashMap where [hash & (length_of_hashmap-1)] is used to find index of key in hashmap.

Length of hashmap is always power of 2 , and in this case segmentmask is also (power of 2)-1.

It works on the same concept of hashmap%size of hashmap, so that index does not go beyond hahsmap's length.

quite right! but there is an exception.

        int sshift = 0;
        int ssize = 1;
        while (ssize < concurrencyLevel) {
            ++sshift;
            ssize <<= 1;
        }
        segmentShift = 32 - sshift;
        segmentMask = ssize - 1; 

when concurrentLevel is 1, the segmentShift is 32, segmentMask is 0. (hash >>> 32) = hash , way cross the limit of the segment array, then you need segmentMask .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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