Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad attempt to compute absolute value

Tags:

java

jenkins

        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?

like image 521
Samarland Avatar asked May 01 '14 20:05

Samarland


1 Answers

The warning itself explains why you're getting the warning.

You're calling 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 Math.abs().

int server = Math.abs(q.hashCode() % solrLoadBalanceNumOfServers) + 1;
like image 157
mattarod Avatar answered Sep 28 '22 17:09

mattarod