Using the bit-shift operator in ConcurrentHashMap

When I was going through the source code of ConcurrentHashMap, I came across so many bit shift operators. Some of them are used to create constants, and some for variables.

static final int MAXIMUM_CAPACITY = 1 << 30; static final int MAX_SEGMENTS = 1 << 16; // slightly conservative long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE; 

I can’t understand if a constant, for example MAXIMUM_CAPACITY, can be declared directly, what to use with the bitwise shift operator.

+5
source share
1 answer

They do not use a number in decimal form (base 10). Instead, they say, β€œThis is a number with 30 trailing 0 bits,” meaning that the number is used for systems with a base of 2.

Battle advancement facilitates informing the reader of the meaning. In base 10, it will represent 1073741824 , which seems like a random number.


This is a common occurrence in programming. For instance:

 int secondsInDay = 60 * 60 * 24; 

We represent the number of seconds per minute, multiplied by the number of minutes per hour, multiplied by the number of hours per day.

We could just put 86400 , but what if we wanted to change the number of minutes per hour (to represent the time on some other planet)? You will need to manually calculate it in order to change the value.

On the other hand, breaking it down into units, as shown above, we can simply change the average 60 to change the number of minutes per day.

+3
source

Source: https://habr.com/ru/post/1236443/


All Articles