1 /* 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 * 4 * This code is free software; you can redistribute it and/or modify it 5 * under the terms of the GNU General Public License version 2 only, as 6 * published by the Free Software Foundation. Oracle designates this 7 * particular file as subject to the "Classpath" exception as provided 8 * by Oracle in the LICENSE file that accompanied this code. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 */ 24 25 /* 26 * This file is available under and governed by the GNU General Public 27 * License version 2 only, as published by the Free Software Foundation. 28 * However, the following notice accompanied the original version of this 29 * file: 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/licenses/publicdomain 34 */ 35 36 package java.util.concurrent; 37 38 import java.util.Random; 39 40 /** 41 * A random number generator isolated to the current thread. Like the 42 * global {@link java.util.Random} generator used by the {@link 43 * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized 44 * with an internally generated seed that may not otherwise be 45 * modified. When applicable, use of {@code ThreadLocalRandom} rather 46 * than shared {@code Random} objects in concurrent programs will 47 * typically encounter much less overhead and contention. Use of 48 * {@code ThreadLocalRandom} is particularly appropriate when multiple 49 * tasks (for example, each a {@link ForkJoinTask}) use random numbers 50 * in parallel in thread pools. 51 * 52 * <p>Usages of this class should typically be of the form: 53 * {@code ThreadLocalRandom.current().nextX(...)} (where 54 * {@code X} is {@code Int}, {@code Long}, etc). 55 * When all usages are of this form, it is never possible to 56 * accidently share a {@code ThreadLocalRandom} across multiple threads. 57 * 58 * <p>This class also provides additional commonly used bounded random 59 * generation methods. 60 * 61 * @since 1.7 62 * @author Doug Lea 63 */ 64 public class ThreadLocalRandom extends Random { 65 // same constants as Random, but must be redeclared because private 66 private final static long multiplier = 0x5DEECE66DL; 67 private final static long addend = 0xBL; 68 private final static long mask = (1L << 48) - 1; 69 70 /** 71 * The random seed. We can't use super.seed. 72 */ 73 private long rnd; 74 75 /** 76 * Initialization flag to permit calls to setSeed to succeed only 77 * while executing the Random constructor. We can't allow others 78 * since it would cause setting seed in one part of a program to 79 * unintentionally impact other usages by the thread. 80 */ 81 boolean initialized; 82 83 // Padding to help avoid memory contention among seed updates in 84 // different TLRs in the common case that they are located near 85 // each other. 86 private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; 87 88 /** 89 * The actual ThreadLocal 90 */ 91 private static final ThreadLocal<ThreadLocalRandom> localRandom = 92 new ThreadLocal<ThreadLocalRandom>() { 93 protected ThreadLocalRandom initialValue() { 94 return new ThreadLocalRandom(); 95 } 96 }; 97 98 99 /** 100 * Constructor called only by localRandom.initialValue. 101 */ 102 ThreadLocalRandom() { 103 super(); 104 initialized = true; 105 } 106 107 /** 108 * Returns the current thread's {@code ThreadLocalRandom}. 109 * 110 * @return the current thread's {@code ThreadLocalRandom} 111 */ 112 public static ThreadLocalRandom current() { 113 return localRandom.get(); 114 } 115 116 /** 117 * Throws {@code UnsupportedOperationException}. Setting seeds in 118 * this generator is not supported. 119 * 120 * @throws UnsupportedOperationException always 121 */ 122 public void setSeed(long seed) { 123 if (initialized) 124 throw new UnsupportedOperationException(); 125 rnd = (seed ^ multiplier) & mask; 126 } 127 128 protected int next(int bits) { 129 rnd = (rnd * multiplier + addend) & mask; 130 return (int) (rnd >>> (48-bits)); 131 } 132 133 /** 134 * Returns a pseudorandom, uniformly distributed value between the 135 * given least value (inclusive) and bound (exclusive). 136 * 137 * @param least the least value returned 138 * @param bound the upper bound (exclusive) 139 * @throws IllegalArgumentException if least greater than or equal 140 * to bound 141 * @return the next value 142 */ 143 public int nextInt(int least, int bound) { 144 if (least >= bound) 145 throw new IllegalArgumentException(); 146 return nextInt(bound - least) + least; 147 } 148 149 /** 150 * Returns a pseudorandom, uniformly distributed value 151 * between 0 (inclusive) and the specified value (exclusive). 152 * 153 * @param n the bound on the random number to be returned. Must be 154 * positive. 155 * @return the next value 156 * @throws IllegalArgumentException if n is not positive 157 */ 158 public long nextLong(long n) { 159 if (n <= 0) 160 throw new IllegalArgumentException("n must be positive"); 161 // Divide n by two until small enough for nextInt. On each 162 // iteration (at most 31 of them but usually much less), 163 // randomly choose both whether to include high bit in result 164 // (offset) and whether to continue with the lower vs upper 165 // half (which makes a difference only if odd). 166 long offset = 0; 167 while (n >= Integer.MAX_VALUE) { 168 int bits = next(2); 169 long half = n >>> 1; 170 long nextn = ((bits & 2) == 0) ? half : n - half; 171 if ((bits & 1) == 0) 172 offset += n - nextn; 173 n = nextn; 174 } 175 return offset + nextInt((int) n); 176 } 177 178 /** 179 * Returns a pseudorandom, uniformly distributed value between the 180 * given least value (inclusive) and bound (exclusive). 181 * 182 * @param least the least value returned 183 * @param bound the upper bound (exclusive) 184 * @return the next value 185 * @throws IllegalArgumentException if least greater than or equal 186 * to bound 187 */ 188 public long nextLong(long least, long bound) { 189 if (least >= bound) 190 throw new IllegalArgumentException(); 191 return nextLong(bound - least) + least; 192 } 193 194 /** 195 * Returns a pseudorandom, uniformly distributed {@code double} value 196 * between 0 (inclusive) and the specified value (exclusive). 197 * 198 * @param n the bound on the random number to be returned. Must be 199 * positive. 200 * @return the next value 201 * @throws IllegalArgumentException if n is not positive 202 */ 203 public double nextDouble(double n) { 204 if (n <= 0) 205 throw new IllegalArgumentException("n must be positive"); 206 return nextDouble() * n; 207 } 208 209 /** 210 * Returns a pseudorandom, uniformly distributed value between the 211 * given least value (inclusive) and bound (exclusive). 212 * 213 * @param least the least value returned 214 * @param bound the upper bound (exclusive) 215 * @return the next value 216 * @throws IllegalArgumentException if least greater than or equal 217 * to bound 218 */ 219 public double nextDouble(double least, double bound) { 220 if (least >= bound) 221 throw new IllegalArgumentException(); 222 return nextDouble() * (bound - least) + least; 223 } 224 225 private static final long serialVersionUID = -5851777807851030925L; 226 } --- EOF ---