Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of bit wise shift operator in ConcurrentHashMap

As I was going through the ConcurrentHashMap source code, I have encountered so many bit wise shift operator. Some are applied on to create constants and some are on 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 am not able to understand, if constant like MAXIMUM_CAPACITY could be declared directly then what is the use of using bitwise shift operator.

like image 348
arham Avatar asked Oct 19 '22 21:10

arham


1 Answers

They are not using the number in decimal form (base 10). Instead, they are saying "this is a number with 30 trailing 0 bits", implying the number is used for base 2 systems.

The bitshifting makes it easier to inform the reader of the value. In base 10, it would represent 1073741824, which seems like a random number.


This is common in programming. For example:

int secondsInDay = 60 * 60 * 24;

We are representing the amount of seconds in a minute, multiplied by the amount of minutes in an hour, multiplied by the amount of hours in a day.

We could have just put 86400, but what if we wanted to change how many minutes are in an hour (to represent time on some other planet)? You would have to manually calculate it to change the value.

On the other hand, by breaking it down into units as shown above, we can simply change the middle 60 to change how many minutes are in a day.

like image 137
Vince Avatar answered Nov 05 '22 08:11

Vince