Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindBugs RV_ABSOLUTE_VALUE_OF_RANDOM_INT warning

Tags:

java

findbugs

I'm trying to do a code review for our project using FindBugs.

we have a method to generate unique id (randomly) :

 public static String generateUUID(int base){

    return String.valueOf(getCurrentTimeInNanos((long)base))  + 

                     String.valueOf(Math.abs(random.nextInt()));
 }

and findBugs indicates RV_ABSOLUTE_VALUE_OF_RANDOM_INT warning (RV: Bad attempt to compute absolute value of signed 32-bit random integer ) , i guess the problem is in String.valueOf(Math.abs(random.nextInt()).

Does anyone have an explanation for why is this and how to fix it ?

like image 801
Mouna Cheikhna Avatar asked Sep 27 '11 10:09

Mouna Cheikhna


1 Answers

Maybe it is because Math.abs can actually return negative results for integer inputs:

assertTrue( Math.abs(Integer.MIN_VALUE) < 0 );

It only does this for MIN_VALUE, though, because -MIN_VALUE cannot be represented. Kind of an overflow problem.

As for how to fix it:

  • don't make your own UUID. Use java.util.UUID.

  • cast the random number to long before calling Math.abs

  • use random.nextInt(Integer.MAX_VALUE) to get a number from 0 to MAX_VALUE - 1

like image 192
Thilo Avatar answered Oct 26 '22 06:10

Thilo