Reputation:
Suppose you have a Java code in which you are using a Random object, initialized with a constant seed. In your code you use the Random object to generate different pseudorandom integers. You are not using multithreading. Is it possible to have different results in different executions of the code? For example, in case that the Java compiler deletes any redundant calls of the Random object in some random way in order to optimize the code, the execution will be different each time if you recompile the code.
Upvotes: 2
Views: 1271
Reputation: 2841
No, this is pretty much guaranteed, assuming the same environement between two runs.
A PRNG can be started from an arbitrary initial state using a seed state. It will always produce the same sequence when initialized with that state
And thank god the optimizer will never change anything with direct consequences on side-effects.
If it removes dead code, it's because the code is deemed dead on each possible state of the program, so no possible impact on the call sequence to Random
.
Upvotes: 0
Reputation: 311458
Unless you introduce any other source of entropy (such as use input or some way the environment can affect the program), the same random seed will produce the same result on every execution.
Note that this relies to the execution of the same byte code. Theoretically, changing your compiler to compile the same source code could produce a different byte code that would produce a different output, but it would be pretty difficult to find a real example to demonstrate this.
Upvotes: 0
Reputation: 12175
I think it should be consistent given you use the same JVM on the same system. I just tried the following.
import java.util.Random;
public class test
{
public static void main(String[] args)
{
Random r = new Random(123);
System.out.println(r.nextInt());
}
}
It gave the same output every time I run it on my machine. I am using Open JDK 1.8.0_91 on Ubuntu 16.04. The value I get when I run this code is -1188957731. Why don't you try to run it and see if you get the same value.
Upvotes: 1
Reputation: 73558
Theoretically a different JVM can use a different implementation for the pseudo random algorithm. Different JVM versions could also do that, since it's not specified anywhere that it needs to return the same values for a given seed between different versions. However as far as I know the Random
implementation in Oracle's JDK has been the same since its inception.
Given the same execution environment the output is guaranteed.
Upvotes: 4