src/share/classes/java/util/concurrent/ThreadLocalRandom.java

Print this page
rev 7009 : 8012645: Stream methods on BitSet, Random, ThreadLocalRandom, ZipFile
Contributed-by: akhil.arora@oracle.com, brian.goetz@oracle.com


  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/publicdomain/zero/1.0/
  34  */
  35 
  36 package java.util.concurrent;
  37 
  38 import java.io.ObjectStreamField;
  39 import java.util.Random;
  40 import java.util.concurrent.atomic.AtomicInteger;
  41 import java.util.concurrent.atomic.AtomicLong;



  42 
  43 /**
  44  * A random number generator isolated to the current thread.  Like the
  45  * global {@link java.util.Random} generator used by the {@link
  46  * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized
  47  * with an internally generated seed that may not otherwise be
  48  * modified. When applicable, use of {@code ThreadLocalRandom} rather
  49  * than shared {@code Random} objects in concurrent programs will
  50  * typically encounter much less overhead and contention.  Use of
  51  * {@code ThreadLocalRandom} is particularly appropriate when multiple
  52  * tasks (for example, each a {@link ForkJoinTask}) use random numbers
  53  * in parallel in thread pools.
  54  *
  55  * <p>Usages of this class should typically be of the form:
  56  * {@code ThreadLocalRandom.current().nextX(...)} (where
  57  * {@code X} is {@code Int}, {@code Long}, etc).
  58  * When all usages are of this form, it is never possible to
  59  * accidently share a {@code ThreadLocalRandom} across multiple threads.
  60  *
  61  * <p>This class also provides additional commonly used bounded random


 222      * @throws IllegalArgumentException if n is not positive
 223      */
 224     public long nextLong(long n) {
 225         if (n <= 0)
 226             throw new IllegalArgumentException("n must be positive");
 227         // Divide n by two until small enough for nextInt. On each
 228         // iteration (at most 31 of them but usually much less),
 229         // randomly choose both whether to include high bit in result
 230         // (offset) and whether to continue with the lower vs upper
 231         // half (which makes a difference only if odd).
 232         long offset = 0;
 233         while (n >= Integer.MAX_VALUE) {
 234             int bits = next(2);
 235             long half = n >>> 1;
 236             long nextn = ((bits & 2) == 0) ? half : n - half;
 237             if ((bits & 1) == 0)
 238                 offset += n - nextn;
 239             n = nextn;
 240         }
 241         return offset + nextInt((int) n);




















 242     }
 243 
 244     /**
 245      * Returns a pseudorandom, uniformly distributed value between the
 246      * given least value (inclusive) and bound (exclusive).
 247      *
 248      * @param least the least value returned
 249      * @param bound the upper bound (exclusive)
 250      * @return the next value
 251      * @throws IllegalArgumentException if least greater than or equal
 252      * to bound
 253      */
 254     public long nextLong(long least, long bound) {
 255         if (least >= bound)
 256             throw new IllegalArgumentException();
 257         return nextLong(bound - least) + least;
 258     }
 259 
 260     /**
 261      * Returns a pseudorandom, uniformly distributed {@code double} value




  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/publicdomain/zero/1.0/
  34  */
  35 
  36 package java.util.concurrent;
  37 
  38 import java.io.ObjectStreamField;
  39 import java.util.Random;
  40 import java.util.concurrent.atomic.AtomicInteger;
  41 import java.util.concurrent.atomic.AtomicLong;
  42 import java.util.stream.DoubleStream;
  43 import java.util.stream.IntStream;
  44 import java.util.stream.LongStream;
  45 
  46 /**
  47  * A random number generator isolated to the current thread.  Like the
  48  * global {@link java.util.Random} generator used by the {@link
  49  * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized
  50  * with an internally generated seed that may not otherwise be
  51  * modified. When applicable, use of {@code ThreadLocalRandom} rather
  52  * than shared {@code Random} objects in concurrent programs will
  53  * typically encounter much less overhead and contention.  Use of
  54  * {@code ThreadLocalRandom} is particularly appropriate when multiple
  55  * tasks (for example, each a {@link ForkJoinTask}) use random numbers
  56  * in parallel in thread pools.
  57  *
  58  * <p>Usages of this class should typically be of the form:
  59  * {@code ThreadLocalRandom.current().nextX(...)} (where
  60  * {@code X} is {@code Int}, {@code Long}, etc).
  61  * When all usages are of this form, it is never possible to
  62  * accidently share a {@code ThreadLocalRandom} across multiple threads.
  63  *
  64  * <p>This class also provides additional commonly used bounded random


 225      * @throws IllegalArgumentException if n is not positive
 226      */
 227     public long nextLong(long n) {
 228         if (n <= 0)
 229             throw new IllegalArgumentException("n must be positive");
 230         // Divide n by two until small enough for nextInt. On each
 231         // iteration (at most 31 of them but usually much less),
 232         // randomly choose both whether to include high bit in result
 233         // (offset) and whether to continue with the lower vs upper
 234         // half (which makes a difference only if odd).
 235         long offset = 0;
 236         while (n >= Integer.MAX_VALUE) {
 237             int bits = next(2);
 238             long half = n >>> 1;
 239             long nextn = ((bits & 2) == 0) ? half : n - half;
 240             if ((bits & 1) == 0)
 241                 offset += n - nextn;
 242             n = nextn;
 243         }
 244         return offset + nextInt((int) n);
 245     }
 246 
 247     @Override
 248     public IntStream ints() {
 249         return IntStream.generate(() -> current().nextInt());
 250     }
 251 
 252     @Override
 253     public LongStream longs() {
 254         return LongStream.generate(() -> current().nextLong());
 255     }
 256 
 257     @Override
 258     public DoubleStream doubles() {
 259         return DoubleStream.generate(() -> current().nextDouble());
 260     }
 261 
 262     @Override
 263     public DoubleStream gaussians() {
 264         return DoubleStream.generate(() -> current().nextGaussian());
 265     }
 266 
 267     /**
 268      * Returns a pseudorandom, uniformly distributed value between the
 269      * given least value (inclusive) and bound (exclusive).
 270      *
 271      * @param least the least value returned
 272      * @param bound the upper bound (exclusive)
 273      * @return the next value
 274      * @throws IllegalArgumentException if least greater than or equal
 275      * to bound
 276      */
 277     public long nextLong(long least, long bound) {
 278         if (least >= bound)
 279             throw new IllegalArgumentException();
 280         return nextLong(bound - least) + least;
 281     }
 282 
 283     /**
 284      * Returns a pseudorandom, uniformly distributed {@code double} value