[concurrency-interest] ThreadLocalRandom initial seed

Aleksey Shipilev aleksey.shipilev at gmail.com
Thu Jun 2 10:29:12 EDT 2011


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();
        }

    }

}


More information about the Concurrency-interest mailing list