I understand that the modulus operation can be optimised using a little & wise magic where the divisor is a power of 2...
Yes, a modulo x % pow(2, n)
can be achieved using x & ((1 << n) - 1)
But the %-operator in java can give different results if x is negative, so blindly substituting one for the other can break code.
When bit-addressing, masking etc. the &-variant is commonly used, as its semantically closer to what is used in assembler/C and signedness is usually not wanted/cared about in that case.
As for if the JIT optimizes % to &, the answer is: it depends entirely on the JIT - and thats a moving target.
In case x % y
where y isn't a constant its pretty difficult to detect if y is a power of 2, so presumably that case isn't optimizable because detecting it is very difficult or impossible. If y is a constant, the JIT still has prove that x isn't negative - or insert a conditional similar to result = x < 0 ? x % y : x & (y-1)
. It may or may not do so, depending on JIT in question and also depending on the platform. At least Hotspot is known to use different optimizations for different processors (of the same ISA, namely AMD vs Intel) in some cases.