rt/emul/compact/src/main/java/java/util/concurrent/ThreadLocalRandom.java
branchjdk7-b147
changeset 1890 212417b74b72
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/rt/emul/compact/src/main/java/java/util/concurrent/ThreadLocalRandom.java	Sat Mar 19 10:46:31 2016 +0100
     1.3 @@ -0,0 +1,226 @@
     1.4 +/*
     1.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.6 + *
     1.7 + * This code is free software; you can redistribute it and/or modify it
     1.8 + * under the terms of the GNU General Public License version 2 only, as
     1.9 + * published by the Free Software Foundation.  Oracle designates this
    1.10 + * particular file as subject to the "Classpath" exception as provided
    1.11 + * by Oracle in the LICENSE file that accompanied this code.
    1.12 + *
    1.13 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.14 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.15 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.16 + * version 2 for more details (a copy is included in the LICENSE file that
    1.17 + * accompanied this code).
    1.18 + *
    1.19 + * You should have received a copy of the GNU General Public License version
    1.20 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.21 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.22 + *
    1.23 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.24 + * or visit www.oracle.com if you need additional information or have any
    1.25 + * questions.
    1.26 + */
    1.27 +
    1.28 +/*
    1.29 + * This file is available under and governed by the GNU General Public
    1.30 + * License version 2 only, as published by the Free Software Foundation.
    1.31 + * However, the following notice accompanied the original version of this
    1.32 + * file:
    1.33 + *
    1.34 + * Written by Doug Lea with assistance from members of JCP JSR-166
    1.35 + * Expert Group and released to the public domain, as explained at
    1.36 + * http://creativecommons.org/publicdomain/zero/1.0/
    1.37 + */
    1.38 +
    1.39 +package java.util.concurrent;
    1.40 +
    1.41 +import java.util.Random;
    1.42 +
    1.43 +/**
    1.44 + * A random number generator isolated to the current thread.  Like the
    1.45 + * global {@link java.util.Random} generator used by the {@link
    1.46 + * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized
    1.47 + * with an internally generated seed that may not otherwise be
    1.48 + * modified. When applicable, use of {@code ThreadLocalRandom} rather
    1.49 + * than shared {@code Random} objects in concurrent programs will
    1.50 + * typically encounter much less overhead and contention.  Use of
    1.51 + * {@code ThreadLocalRandom} is particularly appropriate when multiple
    1.52 + * tasks (for example, each a {@link ForkJoinTask}) use random numbers
    1.53 + * in parallel in thread pools.
    1.54 + *
    1.55 + * <p>Usages of this class should typically be of the form:
    1.56 + * {@code ThreadLocalRandom.current().nextX(...)} (where
    1.57 + * {@code X} is {@code Int}, {@code Long}, etc).
    1.58 + * When all usages are of this form, it is never possible to
    1.59 + * accidently share a {@code ThreadLocalRandom} across multiple threads.
    1.60 + *
    1.61 + * <p>This class also provides additional commonly used bounded random
    1.62 + * generation methods.
    1.63 + *
    1.64 + * @since 1.7
    1.65 + * @author Doug Lea
    1.66 + */
    1.67 +public class ThreadLocalRandom extends Random {
    1.68 +    // same constants as Random, but must be redeclared because private
    1.69 +    private static final long multiplier = 0x5DEECE66DL;
    1.70 +    private static final long addend = 0xBL;
    1.71 +    private static final long mask = (1L << 48) - 1;
    1.72 +
    1.73 +    /**
    1.74 +     * The random seed. We can't use super.seed.
    1.75 +     */
    1.76 +    private long rnd;
    1.77 +
    1.78 +    /**
    1.79 +     * Initialization flag to permit calls to setSeed to succeed only
    1.80 +     * while executing the Random constructor.  We can't allow others
    1.81 +     * since it would cause setting seed in one part of a program to
    1.82 +     * unintentionally impact other usages by the thread.
    1.83 +     */
    1.84 +    boolean initialized;
    1.85 +
    1.86 +    // Padding to help avoid memory contention among seed updates in
    1.87 +    // different TLRs in the common case that they are located near
    1.88 +    // each other.
    1.89 +    private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
    1.90 +
    1.91 +    /**
    1.92 +     * The actual ThreadLocal
    1.93 +     */
    1.94 +    private static final ThreadLocal<ThreadLocalRandom> localRandom =
    1.95 +        new ThreadLocal<ThreadLocalRandom>() {
    1.96 +            protected ThreadLocalRandom initialValue() {
    1.97 +                return new ThreadLocalRandom();
    1.98 +            }
    1.99 +    };
   1.100 +
   1.101 +
   1.102 +    /**
   1.103 +     * Constructor called only by localRandom.initialValue.
   1.104 +     */
   1.105 +    ThreadLocalRandom() {
   1.106 +        super();
   1.107 +        initialized = true;
   1.108 +    }
   1.109 +
   1.110 +    /**
   1.111 +     * Returns the current thread's {@code ThreadLocalRandom}.
   1.112 +     *
   1.113 +     * @return the current thread's {@code ThreadLocalRandom}
   1.114 +     */
   1.115 +    public static ThreadLocalRandom current() {
   1.116 +        return localRandom.get();
   1.117 +    }
   1.118 +
   1.119 +    /**
   1.120 +     * Throws {@code UnsupportedOperationException}.  Setting seeds in
   1.121 +     * this generator is not supported.
   1.122 +     *
   1.123 +     * @throws UnsupportedOperationException always
   1.124 +     */
   1.125 +    public void setSeed(long seed) {
   1.126 +        if (initialized)
   1.127 +            throw new UnsupportedOperationException();
   1.128 +        rnd = (seed ^ multiplier) & mask;
   1.129 +    }
   1.130 +
   1.131 +    protected int next(int bits) {
   1.132 +        rnd = (rnd * multiplier + addend) & mask;
   1.133 +        return (int) (rnd >>> (48-bits));
   1.134 +    }
   1.135 +
   1.136 +    /**
   1.137 +     * Returns a pseudorandom, uniformly distributed value between the
   1.138 +     * given least value (inclusive) and bound (exclusive).
   1.139 +     *
   1.140 +     * @param least the least value returned
   1.141 +     * @param bound the upper bound (exclusive)
   1.142 +     * @throws IllegalArgumentException if least greater than or equal
   1.143 +     * to bound
   1.144 +     * @return the next value
   1.145 +     */
   1.146 +    public int nextInt(int least, int bound) {
   1.147 +        if (least >= bound)
   1.148 +            throw new IllegalArgumentException();
   1.149 +        return nextInt(bound - least) + least;
   1.150 +    }
   1.151 +
   1.152 +    /**
   1.153 +     * Returns a pseudorandom, uniformly distributed value
   1.154 +     * between 0 (inclusive) and the specified value (exclusive).
   1.155 +     *
   1.156 +     * @param n the bound on the random number to be returned.  Must be
   1.157 +     *        positive.
   1.158 +     * @return the next value
   1.159 +     * @throws IllegalArgumentException if n is not positive
   1.160 +     */
   1.161 +    public long nextLong(long n) {
   1.162 +        if (n <= 0)
   1.163 +            throw new IllegalArgumentException("n must be positive");
   1.164 +        // Divide n by two until small enough for nextInt. On each
   1.165 +        // iteration (at most 31 of them but usually much less),
   1.166 +        // randomly choose both whether to include high bit in result
   1.167 +        // (offset) and whether to continue with the lower vs upper
   1.168 +        // half (which makes a difference only if odd).
   1.169 +        long offset = 0;
   1.170 +        while (n >= Integer.MAX_VALUE) {
   1.171 +            int bits = next(2);
   1.172 +            long half = n >>> 1;
   1.173 +            long nextn = ((bits & 2) == 0) ? half : n - half;
   1.174 +            if ((bits & 1) == 0)
   1.175 +                offset += n - nextn;
   1.176 +            n = nextn;
   1.177 +        }
   1.178 +        return offset + nextInt((int) n);
   1.179 +    }
   1.180 +
   1.181 +    /**
   1.182 +     * Returns a pseudorandom, uniformly distributed value between the
   1.183 +     * given least value (inclusive) and bound (exclusive).
   1.184 +     *
   1.185 +     * @param least the least value returned
   1.186 +     * @param bound the upper bound (exclusive)
   1.187 +     * @return the next value
   1.188 +     * @throws IllegalArgumentException if least greater than or equal
   1.189 +     * to bound
   1.190 +     */
   1.191 +    public long nextLong(long least, long bound) {
   1.192 +        if (least >= bound)
   1.193 +            throw new IllegalArgumentException();
   1.194 +        return nextLong(bound - least) + least;
   1.195 +    }
   1.196 +
   1.197 +    /**
   1.198 +     * Returns a pseudorandom, uniformly distributed {@code double} value
   1.199 +     * between 0 (inclusive) and the specified value (exclusive).
   1.200 +     *
   1.201 +     * @param n the bound on the random number to be returned.  Must be
   1.202 +     *        positive.
   1.203 +     * @return the next value
   1.204 +     * @throws IllegalArgumentException if n is not positive
   1.205 +     */
   1.206 +    public double nextDouble(double n) {
   1.207 +        if (n <= 0)
   1.208 +            throw new IllegalArgumentException("n must be positive");
   1.209 +        return nextDouble() * n;
   1.210 +    }
   1.211 +
   1.212 +    /**
   1.213 +     * Returns a pseudorandom, uniformly distributed value between the
   1.214 +     * given least value (inclusive) and bound (exclusive).
   1.215 +     *
   1.216 +     * @param least the least value returned
   1.217 +     * @param bound the upper bound (exclusive)
   1.218 +     * @return the next value
   1.219 +     * @throws IllegalArgumentException if least greater than or equal
   1.220 +     * to bound
   1.221 +     */
   1.222 +    public double nextDouble(double least, double bound) {
   1.223 +        if (least >= bound)
   1.224 +            throw new IllegalArgumentException();
   1.225 +        return nextDouble() * (bound - least) + least;
   1.226 +    }
   1.227 +
   1.228 +    private static final long serialVersionUID = -5851777807851030925L;
   1.229 +}