ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ThreadLocalRandom.java
(Generate patch)

Comparing jsr166/src/jsr166y/ThreadLocalRandom.java (file contents):
Revision 1.1 by dl, Mon Jan 12 17:16:18 2009 UTC vs.
Revision 1.12 by jsr166, Wed Aug 19 17:44:45 2009 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import java.util.*;
8 >
9 > import java.util.Random;
10  
11   /**
12 < * A Random number generator with the same properties as {@link
13 < * Random} but isolated to the current Thread.  Like the global
14 < * generator used by {@link java.lang.Math}, a ThreadLocalRandom is
15 < * initialized with an internally generated seed that may not
16 < * otherwise be modified. When applicable, use of ThreadLocalRandom
17 < * rather than shared Random objects in concurrent programs will
18 < * typically encounter less overhead and contention. The most common
19 < * usage form is: <code>ThreadLocalRandom.current().nextX()</code>.
12 > * A random number generator isolated to the current Thread.  Like the
13 > * global {@link java.util.Random} generator used by the {@link
14 > * java.lang.Math} class, a ThreadLocalRandom is initialized with an
15 > * internally generated seed that may not otherwise be modified. When
16 > * applicable, use of ThreadLocalRandom rather than shared Random
17 > * objects in concurrent programs will typically encounter much less
18 > * overhead and contention.  ThreadLocalRandoms are particularly
19 > * appropriate when multiple tasks (for example, each a {@link
20 > * ForkJoinTask}), use random numbers in parallel in thread pools.
21 > *
22 > * <p>Usages of this class should typically be of the form:
23 > * {@code ThreadLocalRandom.current().nextX(...)} (where
24 > * {@code X} is {@code Int}, {@code Long}, etc).
25 > * When all usages are of this form, it is never possible to
26 > * accidently share ThreadLocalRandoms across multiple threads.
27   *
28   * <p>This class also provides additional commonly used bounded random
29   * generation methods.
30 + *
31 + * @since 1.7
32 + * @author Doug Lea
33   */
34   public class ThreadLocalRandom extends Random {
35      // same constants as Random, but must be redeclared because private
# Line 27 | Line 38 | public class ThreadLocalRandom extends R
38      private final static long mask = (1L << 48) - 1;
39  
40      /**
41 <     * The random seed. We can't use super.seed
41 >     * The random seed. We can't use super.seed.
42       */
43 <    private long rnd;
43 >    private long rnd;
44  
45      /**
46       * Initialization flag to permit the first and only allowed call
47       * to setSeed (inside Random constructor) to succeed.  We can't
48       * allow others since it would cause setting seed in one part of a
49 <     * program to inintentionally impact other usages by the thread.
49 >     * program to unintentionally impact other usages by the thread.
50       */
51      boolean initialized;
52  
# Line 44 | Line 55 | public class ThreadLocalRandom extends R
55      // each other.
56      private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
57  
58 +    /**
59 +     * The actual ThreadLocal
60 +     */
61      private static final ThreadLocal<ThreadLocalRandom> localRandom =
62          new ThreadLocal<ThreadLocalRandom>() {
63              protected ThreadLocalRandom initialValue() {
# Line 51 | Line 65 | public class ThreadLocalRandom extends R
65              }
66      };
67  
68 <    ThreadLocalRandom() { // construct only in localRandom.initialValue
69 <        super(); // super constructor calls setSeed
68 >
69 >    /**
70 >     * Constructor called only by localRandom.initialValue.
71 >     * We rely on the fact that the superclass no-arg constructor
72 >     * invokes setSeed exactly once to initialize.
73 >     */
74 >    ThreadLocalRandom() {
75 >        super();
76      }
77  
78      /**
79 <     * Returns the current Thread's ThreadLocalRandom
79 >     * Returns the current Thread's ThreadLocalRandom.
80 >     *
81       * @return the current Thread's ThreadLocalRandom
82       */
83      public static ThreadLocalRandom current() {
# Line 64 | Line 85 | public class ThreadLocalRandom extends R
85      }
86  
87      /**
88 <     * Throws UnsupportedOperationException. Setting seeds in this
89 <     * generator is unsupported.
90 <     * @throw UnsupportedOperationException always
88 >     * Throws {@code UnsupportedOperationException}.  Setting seeds in
89 >     * this generator is not supported.
90 >     *
91 >     * @throws UnsupportedOperationException always
92       */
93 <    public void setSeed(long seed) {
93 >    public void setSeed(long seed) {
94          if (initialized)
95              throw new UnsupportedOperationException();
96          initialized = true;
# Line 76 | Line 98 | public class ThreadLocalRandom extends R
98      }
99  
100      protected int next(int bits) {
101 <        return (int)((rnd = (rnd * multiplier + addend) & mask) >>> (48-bits));
101 >        rnd = (rnd * multiplier + addend) & mask;
102 >        return (int) (rnd >>> (48-bits));
103      }
104  
105      /**
106       * Returns a pseudorandom, uniformly distributed value between the
107       * given least value (inclusive) and bound (exclusive).
108 +     *
109       * @param least the least value returned
110       * @param bound the upper bound (exclusive)
111       * @throws IllegalArgumentException if least greater than or equal
# Line 96 | Line 120 | public class ThreadLocalRandom extends R
120  
121      /**
122       * Returns a pseudorandom, uniformly distributed value
123 <     * between 0 (inclusive) and the specified value (exclusive)
123 >     * between 0 (inclusive) and the specified value (exclusive).
124 >     *
125       * @param n the bound on the random number to be returned.  Must be
126       *        positive.
127       * @return the next value
# Line 105 | Line 130 | public class ThreadLocalRandom extends R
130      public long nextLong(long n) {
131          if (n <= 0)
132              throw new IllegalArgumentException("n must be positive");
133 +        // Divide n by two until small enough for nextInt. On each
134 +        // iteration (at most 31 of them but usually much less),
135 +        // randomly choose both whether to include high bit in result
136 +        // (offset) and whether to continue with the lower vs upper
137 +        // half (which makes a difference only if odd).
138          long offset = 0;
139 <        while (n >= Integer.MAX_VALUE) { // randomly pick half range
140 <            int bits = next(2); // 2nd bit for odd vs even split
139 >        while (n >= Integer.MAX_VALUE) {
140 >            int bits = next(2);
141              long half = n >>> 1;
142 <            long nextn = ((bits & 2) == 0)? half : n - half;
142 >            long nextn = ((bits & 2) == 0) ? half : n - half;
143              if ((bits & 1) == 0)
144                  offset += n - nextn;
145              n = nextn;
146          }
147 <        return offset + nextInt((int)n);
147 >        return offset + nextInt((int) n);
148      }
149  
150      /**
151       * Returns a pseudorandom, uniformly distributed value between the
152       * given least value (inclusive) and bound (exclusive).
153 +     *
154       * @param least the least value returned
155       * @param bound the upper bound (exclusive)
156       * @return the next value
# Line 134 | Line 165 | public class ThreadLocalRandom extends R
165  
166      /**
167       * Returns a pseudorandom, uniformly distributed {@code double} value
168 <     * between 0 (inclusive) and the specified value (exclusive)
168 >     * between 0 (inclusive) and the specified value (exclusive).
169 >     *
170       * @param n the bound on the random number to be returned.  Must be
171       *        positive.
172       * @return the next value
# Line 149 | Line 181 | public class ThreadLocalRandom extends R
181      /**
182       * Returns a pseudorandom, uniformly distributed value between the
183       * given least value (inclusive) and bound (exclusive).
184 +     *
185       * @param least the least value returned
186       * @param bound the upper bound (exclusive)
187       * @return the next value
# Line 161 | Line 194 | public class ThreadLocalRandom extends R
194          return nextDouble() * (bound - least) + least;
195      }
196  
197 < }
197 >    private static final long serialVersionUID = -5851777807851030925L;
198 > }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines