Random over ThreadLocalRandom

后端 未结 6 1867
梦谈多话
梦谈多话 2020-12-02 22:48

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention an

6条回答
  •  生来不讨喜
    2020-12-02 23:15

    There are some problems with ThreadLocalRandom, that you cannot control the initial seed. I also don't find a working set seed method somewhere.

    It should be noted that there is contention when multiple threads use Math.random(), since they will under the hood access a shared instance of the class Random, there is an alternative in using ThreadLocalRandom which also solves the seed problem.

    ThreadLocalRandom uses a seed stashed into the Thread. And they decided to do the initial seed for you, without any means to control it. You can equally well create your own instance of Random and use it in a thread local fashion. So if you do the following:

    /* my thread */
    rnd = new Random(my_seed);
    /* use rnd */
    

    You will also see no contention. And using the same seed, you get reproducable random sequences, which can help in testing. When you have multiple threads you can distribute seeds over these threads. There should be algorithms around to generate good distance seeds.

提交回复
热议问题