[concurrency-interest] ThreadLocalRandom initial seed
Kasper Nielsen
kasper at kav.dk
Thu Jun 2 17:43:51 EDT 2011
Good catch,
that is definitely a bug.
Looks like the fix to
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6937857
introduced a non-compatible change by not calling setSeed() in
Random(long seed) anymore.
Cheers
Kasper
On 02-06-2011 16:29, Aleksey Shipilev wrote:
> Hi,
>
> I've been stumbled upon ThreadLocalRandom seed behavior. JavaDoc
> reads: "ThreadLocalRandom is initialized with an internally generated
> seed that may not otherwise be modified." I would expect TLR called in
> several threads concurrently to have different global values. But
> apparently the internal seed in TLR always has the same seed (which is
> default value for long).
>
> Is this intentional? Or just oversight that should be fixed?
>
> I.e. I would expect my test [1] print all-different values per thread,
> like regular Random does.
>
> That's what happens now:
>
> Regular thread-local Random
> 780
> 4307
> 9112
> 4368
> 6673
> ========
> 4143
> 4905
> 2331
> 154
> 2887
> ========
> 9586
> 6161
> 9948
> 4179
> 3608
> ========
>
> ThreadLocalRandom
> 0
> 6118
> 1895
> 7186
> 7366
> ========
> 0
> 6118
> 1895
> 7186
> 7366
> ========
> 0
> 6118
> 1895
> 7186
> 7366
> ========
>
> Thanks,
> Aleksey.
>
> [1]
> import java.util.Random;
> import java.util.concurrent.ThreadLocalRandom;
>
> public class Main {
>
> public static ThreadLocal<Random> random = new ThreadLocal<Random>() {
> @Override
> protected Random initialValue() {
> return new Random();
> }
> };
>
> public static void main(String[] args) throws InterruptedException {
>
> System.out.println("Regular thread-local Random");
> for (int i = 0; i< 3; i++) {
> Thread t = new Thread(new Runnable() {
> @Override
> public void run() {
> for (int c = 0; c< 5; c++) {
> System.out.println(random.get().nextInt(10000));
> }
> System.out.println("========");
> }
> });
> t.start();
> t.join();
> }
>
> System.out.println("ThreadLocalRandom");
> for (int i = 0; i< 5; i++) {
> Thread t = new Thread(new Runnable() {
> @Override
> public void run() {
> for (int c = 0; c< 5; c++) {
>
> System.out.println(ThreadLocalRandom.current().nextLong(10000));
> }
> System.out.println("========");
> }
> });
> t.start();
> t.join();
> }
>
> }
>
> }
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>
More information about the Concurrency-interest
mailing list