当前位置:网站首页>Jvmrandom cannot set seeds | problem tracing | source code tracing

Jvmrandom cannot set seeds | problem tracing | source code tracing

2022-07-05 19:50:00 Bulst

Last article , We introduce several generation strategies of random numbers .

So next , Let's analyze JVMRandom The problem is .

When we normally construct a random number as follows , There is no problem .

JVMRandom jvmRandom = new JVMRandom();
int i = jvmRandom.nextInt(10);
System.out.println(i);

since JVMRandom The underlying call is Random Constructor for , Can it also be set seed Is it worth it ?

So let's verify that

JVMRandom jvmRandom = new JVMRandom();
jvmRandom.setSeed(2);
int i = jvmRandom.nextInt(10);
System.out.println(i);

Shua ~ Wrong report

Exception in thread "main" java.lang.UnsupportedOperationException
	at org.apache.commons.lang.math.JVMRandom.setSeed(JVMRandom.java:71)
	at com.ossa.producer.controller.ProducerController.main(ProducerController.java:61)

Let's take a look at the source code , To find out .

 Insert picture description here
JVMRandom Inherited Random, Rewrite the setSeed Method .

And setting seed value is no longer supported .

Source code is as follows , When constructed The value is false when , Will throw an exception .

    /** * Unsupported in 2.0. * * @param seed ignored * @throws UnsupportedOperationException */
    public synchronized void setSeed(long seed) {
    
        if (this.constructed) {
    
            throw new UnsupportedOperationException();
        }
    }

Go back to constructed value , The default is false

    /** * Ensures that only the parent constructor can call reseed. */
    private boolean constructed = false;

however , By observing its structure, we can find , It has only one parameterless constructor .

 Insert picture description here
Let's see what it looks like

/** * Constructs a new instance. */
public JVMRandom() {
    
    this.constructed = true;
}

Oh , Then there's no way out , in other words , If we want to use it JVMRandom To construct random numbers , The object must be created through the parameterless constructor , that constructed It must be true, therefore , If you call setSeed Method , Then the above exception will be thrown .

原网站

版权声明
本文为[Bulst]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051946354008.html

随机推荐