I want to know if there is a way to βpredictβ the next generated number and how does the JVM determine which number to generate next?
Absolutely. The Random class is implemented as a linear congruent number generator (LCNG). The general formula for a linear congruent generator is:
new_state = (old_state * C1 + C2) modulo N
The exact algorithm used by Random is specified in javadocs . If you know the current state of generator 1, the next state is completely predictable.
Will my code output be close to real random in any JVM and OS?
If you use Random , then no. Not for any JVM on any OS.
The sequence generated by the LCNG is definitely not random and has statistical properties that differ significantly from the true random sequence. (The sequence will be strictly automatically correlated, and it will be displayed if you display the results of consecutive calls in Random.nextInt() .)
This is problem? Well, it depends on what your application needs. If you need "random" numbers that are difficult to predict (for example, for a security-related algorithm), then obviously not. And if numbers will be used for Monte Carlo simulations, then automatic LCNG correlation can distort the simulations. But if you just build a solitaire card game ... maybe that doesn't matter.
1 - For clarity, the state of a Random object consists of the values ββof its instance variables; see source code You can check them using the debugger. As a last resort, you can access them and even update them using Java reflection, but I would not recommend doing this. The "previous" state is not recorded.
source share