int server = (Math.abs(q.hashCode()) % solrLoadBalanceNumOfServers) + 1;
Jenkins is warning me with this note:
Bad attempt to compute absolute value of signed 32-bit hashcode
This code generates a hashcode and then computes the absolute value of that hashcode. If the hashcode is
Integer.MIN_VALUE, then the result will be negative as well (since
Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE).
One out of 2^32 strings have a hashCode of
Integer.MIN_VALUE, including “polygenelubricants” “GydZG_” and “”DESIGNING WORKHOUSES”.
Does anyone know why I got this warning for this compute absolute value?
The warning itself explains why you’re getting the warning.
Math.abs() on a hashcode. Integers go from −2,147,483,648 to 2,147,483,647. Since the maximum is 2,147,483,647,
Math.abs(-2,147,483,648) returns -2,147,483,648 because there is no 2,147,483,648. If your String hashcodes to -2,147,483,648, then the
server variable will be assigned to a negative value, which may cause the query to be dropped or your service to crash.
Rather than do it that way, just do the modulus first and then call
int server = Math.abs(q.hashCode() % solrLoadBalanceNumOfServers) + 1;
First the error is likely coming from FindBugs(link) not Jenkins itself. It is just being run/shown in Jenkins.
Integer.MIN_VALUE = -(2^31) and a Integer.MAX_VALUE = 2^31-1. So from a purely mathematical perspective the absolute value of Integer.MIN_VALUE does NOT equal Integer.MAX_VALUE. It will come up infrequently and could cause issues, which is why it is warning you.