Mar 18, 2012

Random / Math.random() / ThreadLocalRandom


java.util.Random 亂數演算法會依賴 seed 數值產生亂數,並在產生亂數後重新產生 seed,
在 Multi-thread 下為了保證在各Thread取到不同的亂數, java.util.Random 在實作上使用 optimistic locking 來同步更換 seed ,問題是若所有Thread都使用同個Random物件產生亂數,在大量競爭下會造成不斷的loop計算,進而產生效能問題

    public Random() {
        this(seedUniquifier() ^ System.nanoTime());

    private static long seedUniquifier() {
        // L'Ecuyer, "Tables of Linear Congruential Generators of
        // Different Sizes and Good Lattice Structure", 1999
        for (;;) {
            long current = seedUniquifier.get();
            long next = current * 181783497276652981L;
            if (seedUniquifier.compareAndSet(current, next))
                return next;

    private static final AtomicLong seedUniquifier
        = new AtomicLong(8682522807148012L);
    public Random(long seed) {
        this.seed = new AtomicLong(initialScramble(seed));

    private static long initialScramble(long seed) {
        return (seed ^ multiplier) & mask;

    protected int next(int bits) {
        long oldseed, nextseed;
        AtomicLong seed = this.seed;
        do {
            oldseed = seed.get();
            nextseed = (oldseed * multiplier + addend) & mask;
        } while (!seed.compareAndSet(oldseed, nextseed));
        return (int)(nextseed >>> (48 - bits));

    public int nextInt() {
        return next(32);

Math.random() 是封裝單個 Random 物件的 helper method,基本上就是JVM共享同個Random物件
    private static Random randomNumberGenerator;

    private static synchronized Random initRNG() {
        Random rnd = randomNumberGenerator;
        return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd;
    public static double random() {
        Random rnd = randomNumberGenerator;
        if (rnd == null) rnd = initRNG();
        return rnd.nextDouble();

    private static final ThreadLocal< Random > localRandom =
        new ThreadLocal< Random >() {
            protected Random initialValue() {
                return new Random();
    public static Random current() {
        return localRandom.get();

JDK7提供的 java.util.concurrent.ThreadLocalRandom,概念類似上方ThreadLocal的方法,API 使用方式如下
int r = ThreadLocalRandom.current().nextInt(4, 77);



Anbarasan14 said...

Great informative post. Thanks for sharing; Do post more blogs of this kind.

Spoken English Classes in Chennai
Spoken English Class in Chennai
Spoken English in Chennai
English Speaking Classes in Mumbai
English Speaking Course in Mumbai
IELTS Coaching in Chennai
IELTS Coaching Centre in Chennai
IELTS Classes in Mumbai
IELTS Coaching in Mumbai

sudhan said...

Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too please do keep sharing more blogs like this.
Cyber Security Training Course in Chennai | Certification | Cyber Security Online Training Course | Ethical Hacking Training Course in Chennai | Certification | Ethical Hacking Online Training Course | CCNA Training Course in Chennai | Certification | CCNA Online Training Course | RPA Robotic Process Automation Training Course in Chennai | Certification | RPA Training Course Chennai | SEO Training in Chennai | Certification | SEO Online Training Course

haseeb said...

Adobe InCopy 2022 Free Download New and latest Version for Windows. It is full offline installer standalone setup of Adobe InCopy 2022 Free .

tech said...

HitmanPro HitmanPro logo · Open HitmanPro · Click on Settings in the bottom left corner · Go to the License tab · Enter your product key, including hyphens · Click . Install Hitman Prok

Anonymous said...

This is because of|as a end result of} developers like Big Time Gaming, Pragmatic Play and Blueprint Gaming who supply demo slots are additionally suspect to strict monitoring and regulations. "Skill 카지노 cease" buttons were added to some slot machines by Zacharias Anthony in the early 1970s. The unique conversion was applied to roughly 50 late-model Bally slot machines. Because the standard machine stopped the reels mechanically in lower than 10 seconds, weights were added to the mechanical timers to extend the automatic stopping of the reels. By the time the New Jersey Alcoholic Beverages Commission had permitted the conversion for use in New Jersey arcades, the word was out and every different distributor began adding skill stops.

tech said...

TMT Steel or TMX steel is the best bet for house construction. They are the latest generation of reinforcement steel (high-strength and .Which Steel Is Best