Java 7: ThreadLocalRandom generating the same random numbers

前端 未结 3 1215
眼角桃花
眼角桃花 2020-12-31 05:38

I\'m trying out Java 7\'s ThreadLocalRandom and see that it is generating exactly the same random numbers across multiple threads.

Here is my code, in which I creat

相关标签:
3条回答
  • 2020-12-31 05:41

    Isn't this because the threads are being created at roughly the same time and thus getting seeded the same value from the timer? I was under the impression that was how that worked, though I may be mistaken.

    0 讨论(0)
  • 2020-12-31 05:45

    Seems like there's an open bug regarding this issue. See here and here

    0 讨论(0)
  • 2020-12-31 05:58

    googling for the "ThreadLocalRandom source" gave me http://www.assembla.com/code/scala-eclipse-toolchain/git/nodes/src/forkjoin/scala/concurrent/forkjoin/ThreadLocalRandom.java

    long/short of it: it uses a ThreadLocal<ThreadLocalRandom> which calls the no-arg constructor for construction

    that no-arg constructor is

    /**
     * Constructor called only by localRandom.initialValue.
     * We rely on the fact that the superclass no-arg constructor
     * invokes setSeed exactly once to initialize.
     */
    ThreadLocalRandom() {
        super();
    }
    

    the no-arg super in Random calls this(long) with a unique seed

    HOWEVER that constructor does

    public Random(long seed) {
        this.seed = new AtomicLong(initialScramble(seed));
    }
    

    i.e. not the expected behavior from documentation

    and ThreadLocalRandom doesn't/can't use the private seed

    0 讨论(0)
提交回复
热议问题