9

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 ?

1 Answer 1

19

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

1
  • 1
    Since there is no random.nextLong(long) method, you can use use this as a quick hack: Math.abs( Math.max(random.nextLong(), Long.MIN_VALUE + 1)) : guarantees a result in the range 0..Long.MAX_VALUE. Commented Jul 1, 2020 at 5:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.