bit and

When I was looking at the source code before, there were many places where the length or the value was set to the N power of 2. I didn't know why?

When looking at the HashedWheelTimer code today

private static int normalizeTicksPerWheel(int ticksPerWheel) {
    int normalizedTicksPerWheel = 1;
    while (normalizedTicksPerWheel < ticksPerWheel) {
        normalizedTicksPerWheel <<= 1;
    }
    return normalizedTicksPerWheel;
}

In the above code, normalizeTicksPerWheel obtains the size of the ring, taking an integer greater than or equal to ticksPerWheel and an N-th power of 2. Why take 2 to the power of N? Mainly because it is very convenient to find the index on the ring whose size is the N-th power of 2, a & (b-1) = a % b, which is true when b is the N-th power of 2.

Why use bitwise AND instead of %?

Since the bit operation directly operates on the memory data, it does not need to be converted into decimal, so the processing speed is very fast

Common skills

a & (b-1) = a % b, which is true when b is the power of 2.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325768289&siteId=291194637
Bit
BIT