Search code examples
javarandom

When should I bother about RandomGenerator.isDeprecated()?


In my Java 17 code I came across the method new Random().isDeprecated() (which returns a boolean) and was wondering how it should be used from a developer perspective.

Can I easily ignore it while doing non-security and non-cryptography related stuff with Random?


Solution

  • Yes, you can ignore it.

    The standard random number generators (SecureRandom.getInstanceStrong() and new Random()) won't be deprecated.

    Whenever you call e.g. rnd.nextInt(), that rnd didn't fall out of the sky. Either [A] you made it, or [B] it was provided to you e.g. as a parameter or set in the constructor of the class that contains the call to .nextInt(). Given that the caller decided to hand you a deprecated algorithm, roll with it. They evidently wanted it that way.

    Where it could potentially be useful is something exotic like this:

    As a setting in a file or in some settings dialog, you allow the user of your application to pick the RNG algorithm. You use this to create an instance of Random (instead of new Random()) and would like to let the user know if they picked a deprecated algorithm, e.g. by adding a warning icon (yellow triangle with an exclamation mark for example) and the text: "CAREFUL: You have chosen a deprecated RNG algorithm. You may want to choose a different one, or pick the default instead".

    Then isDeprecated() can help.