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

Comparing jsr166/src/main/java/util/Random.java (file contents):
Revision 1.4 by jsr166, Fri Nov 7 01:36:42 2003 UTC vs.
Revision 1.30 by jsr166, Mon Jun 6 19:00:28 2011 UTC

# Line 1 | Line 1
1   /*
2 < * %W% %E%
2 > * Copyright (c) 1995, 2010, Oracle and/or its affiliates. All rights reserved.
3 > * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5 < * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
6 < * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
5 > * This code is free software; you can redistribute it and/or modify it
6 > * under the terms of the GNU General Public License version 2 only, as
7 > * published by the Free Software Foundation.  Oracle designates this
8 > * particular file as subject to the "Classpath" exception as provided
9 > * by Oracle in the LICENSE file that accompanied this code.
10 > *
11 > * This code is distributed in the hope that it will be useful, but WITHOUT
12 > * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 > * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 > * version 2 for more details (a copy is included in the LICENSE file that
15 > * accompanied this code).
16 > *
17 > * You should have received a copy of the GNU General Public License version
18 > * 2 along with this work; if not, write to the Free Software Foundation,
19 > * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 > *
21 > * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 > * or visit www.oracle.com if you need additional information or have any
23 > * questions.
24   */
25  
26   package java.util;
27   import java.io.*;
28   import java.util.concurrent.atomic.AtomicLong;
29 + import sun.misc.Unsafe;
30  
31   /**
32 < * An instance of this class is used to generate a stream of
33 < * pseudorandom numbers. The class uses a 48-bit seed, which is
34 < * modified using a linear congruential formula. (See Donald Knuth,
35 < * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
32 > * An instance of this class is used to generate a stream of
33 > * pseudorandom numbers. The class uses a 48-bit seed, which is
34 > * modified using a linear congruential formula. (See Donald Knuth,
35 > * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
36   * <p>
37 < * If two instances of <code>Random</code> are created with the same
38 < * seed, and the same sequence of method calls is made for each, they
39 < * will generate and return identical sequences of numbers. In order to
40 < * guarantee this property, particular algorithms are specified for the
41 < * class <tt>Random</tt>. Java implementations must use all the algorithms
42 < * shown here for the class <tt>Random</tt>, for the sake of absolute
43 < * portability of Java code. However, subclasses of class <tt>Random</tt>
44 < * are permitted to use other algorithms, so long as they adhere to the
37 > * If two instances of {@code Random} are created with the same
38 > * seed, and the same sequence of method calls is made for each, they
39 > * will generate and return identical sequences of numbers. In order to
40 > * guarantee this property, particular algorithms are specified for the
41 > * class {@code Random}. Java implementations must use all the algorithms
42 > * shown here for the class {@code Random}, for the sake of absolute
43 > * portability of Java code. However, subclasses of class {@code Random}
44 > * are permitted to use other algorithms, so long as they adhere to the
45   * general contracts for all the methods.
46   * <p>
47 < * The algorithms implemented by class <tt>Random</tt> use a
48 < * <tt>protected</tt> utility method that on each invocation can supply
47 > * The algorithms implemented by class {@code Random} use a
48 > * {@code protected} utility method that on each invocation can supply
49   * up to 32 pseudorandomly generated bits.
50   * <p>
51 < * Many applications will find the <code>random</code> method in
52 < * class <code>Math</code> simpler to use.
51 > * Many applications will find the method {@link Math#random} simpler to use.
52 > *
53 > * <p>Instances of {@code java.util.Random} are threadsafe.
54 > * However, the concurrent use of the same {@code java.util.Random}
55 > * instance across threads may encounter contention and consequent
56 > * poor performance. Consider instead using
57 > * {@link java.util.concurrent.ThreadLocalRandom} in multithreaded
58 > * designs.
59 > *
60 > * <p>Instances of {@code java.util.Random} are not cryptographically
61 > * secure.  Consider instead using {@link java.security.SecureRandom} to
62 > * get a cryptographically secure pseudo-random number generator for use
63 > * by security-sensitive applications.
64   *
65   * @author  Frank Yellin
66 < * @version %I%, %G%
37 < * @see     java.lang.Math#random()
38 < * @since   JDK1.0
66 > * @since   1.0
67   */
68   public
69   class Random implements java.io.Serializable {
# Line 46 | Line 74 | class Random implements java.io.Serializ
74       * The internal state associated with this pseudorandom number generator.
75       * (The specs for the methods in this class describe the ongoing
76       * computation of this value.)
49     *
50     * @serial
77       */
78 <    private AtomicLong seed;
78 >    private final AtomicLong seed;
79  
80 <    private final static long multiplier = 0x5DEECE66DL;
81 <    private final static long addend = 0xBL;
82 <    private final static long mask = (1L << 48) - 1;
80 >    private static final long multiplier = 0x5DEECE66DL;
81 >    private static final long addend = 0xBL;
82 >    private static final long mask = (1L << 48) - 1;
83  
84      /**
85       * Creates a new random number generator. This constructor sets
86       * the seed of the random number generator to a value very likely
87       * to be distinct from any other invocation of this constructor.
88       */
89 <    public Random() { this(++seedUniquifier + System.nanoTime()); }
90 <    private static volatile long seedUniquifier = 8682522807148012L;
89 >    public Random() {
90 >        this(seedUniquifier() ^ System.nanoTime());
91 >    }
92 >
93 >    private static long seedUniquifier() {
94 >        // L'Ecuyer, "Tables of Linear Congruential Generators of
95 >        // Different Sizes and Good Lattice Structure", 1999
96 >        for (;;) {
97 >            long current = seedUniquifier.get();
98 >            long next = current * 181783497276652981L;
99 >            if (seedUniquifier.compareAndSet(current, next))
100 >                return next;
101 >        }
102 >    }
103 >
104 >    private static final AtomicLong seedUniquifier
105 >        = new AtomicLong(8682522807148012L);
106  
107 <    /**
108 <     * Creates a new random number generator using a single
109 <     * <code>long</code> seed:
110 <     * <blockquote><pre>
111 <     * public Random(long seed) { setSeed(seed); }</pre></blockquote>
112 <     * Used by method <tt>next</tt> to hold
113 <     * the state of the pseudorandom number generator.
107 >    /**
108 >     * Creates a new random number generator using a single {@code long} seed.
109 >     * The seed is the initial value of the internal state of the pseudorandom
110 >     * number generator which is maintained by method {@link #next}.
111 >     *
112 >     * <p>The invocation {@code new Random(seed)} is equivalent to:
113 >     *  <pre> {@code
114 >     * Random rnd = new Random();
115 >     * rnd.setSeed(seed);}</pre>
116       *
117 <     * @param   seed   the initial seed.
118 <     * @see     java.util.Random#setSeed(long)
117 >     * @param seed the initial seed
118 >     * @see   #setSeed(long)
119       */
120      public Random(long seed) {
121 <        this.seed = new AtomicLong(0L);
122 <        setSeed(seed);
121 >        if (getClass() == Random.class)
122 >            this.seed = new AtomicLong(initialScramble(seed));
123 >        else {
124 >            // subclass might have overriden setSeed
125 >            this.seed = new AtomicLong();
126 >            setSeed(seed);
127 >        }
128 >    }
129 >
130 >    private static long initialScramble(long seed) {
131 >        return (seed ^ multiplier) & mask;
132      }
133  
134      /**
135 <     * Sets the seed of this random number generator using a single
136 <     * <code>long</code> seed. The general contract of <tt>setSeed</tt>
137 <     * is that it alters the state of this random number generator
138 <     * object so as to be in exactly the same state as if it had just
139 <     * been created with the argument <tt>seed</tt> as a seed. The method
140 <     * <tt>setSeed</tt> is implemented by class Random as follows:
141 <     * <blockquote><pre>
142 <     * synchronized public void setSeed(long seed) {
143 <     *       this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
144 <     *       haveNextNextGaussian = false;
145 <     * }</pre></blockquote>
146 <     * The implementation of <tt>setSeed</tt> by class <tt>Random</tt>
147 <     * happens to use only 48 bits of the given seed. In general, however,
148 <     * an overriding method may use all 64 bits of the long argument
149 <     * as a seed value.
98 <     *
99 <     * Note: Although the seed value is an AtomicLong, this method
100 <     *       must still be synchronized to ensure correct semantics
101 <     *       of haveNextNextGaussian.
135 >     * Sets the seed of this random number generator using a single
136 >     * {@code long} seed. The general contract of {@code setSeed} is
137 >     * that it alters the state of this random number generator object
138 >     * so as to be in exactly the same state as if it had just been
139 >     * created with the argument {@code seed} as a seed. The method
140 >     * {@code setSeed} is implemented by class {@code Random} by
141 >     * atomically updating the seed to
142 >     *  <pre>{@code (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)}</pre>
143 >     * and clearing the {@code haveNextNextGaussian} flag used by {@link
144 >     * #nextGaussian}.
145 >     *
146 >     * <p>The implementation of {@code setSeed} by class {@code Random}
147 >     * happens to use only 48 bits of the given seed. In general, however,
148 >     * an overriding method may use all 64 bits of the {@code long}
149 >     * argument as a seed value.
150       *
151 <     * @param   seed   the initial seed.
151 >     * @param seed the initial seed
152       */
153      synchronized public void setSeed(long seed) {
154 <        seed = (seed ^ multiplier) & mask;
155 <        this.seed.set(seed);
108 <        haveNextNextGaussian = false;
154 >        this.seed.set(initialScramble(seed));
155 >        haveNextNextGaussian = false;
156      }
157  
158      /**
159 <     * Generates the next pseudorandom number. Subclass should
160 <     * override this, as this is used by all other methods.<p>
161 <     * The general contract of <tt>next</tt> is that it returns an
162 <     * <tt>int</tt> value and if the argument bits is between <tt>1</tt>
163 <     * and <tt>32</tt> (inclusive), then that many low-order bits of the
164 <     * returned value will be (approximately) independently chosen bit
165 <     * values, each of which is (approximately) equally likely to be
166 <     * <tt>0</tt> or <tt>1</tt>. The method <tt>next</tt> is implemented
167 <     * by class <tt>Random</tt> as follows:
168 <     * <blockquote><pre>
169 <     * synchronized protected int next(int bits) {
170 <     *       seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
171 <     *       return (int)(seed >>> (48 - bits));
172 <     * }</pre></blockquote>
173 <     * This is a linear congruential pseudorandom number generator, as
174 <     * defined by D. H. Lehmer and described by Donald E. Knuth in <i>The
175 <     * Art of Computer Programming,</i> Volume 2: <i>Seminumerical
176 <     * Algorithms</i>, section 3.2.1.
177 <     *
178 <     * @param   bits random bits
179 <     * @return  the next pseudorandom value from this random number generator's sequence.
180 <     * @since   JDK1.1
159 >     * Generates the next pseudorandom number. Subclasses should
160 >     * override this, as this is used by all other methods.
161 >     *
162 >     * <p>The general contract of {@code next} is that it returns an
163 >     * {@code int} value and if the argument {@code bits} is between
164 >     * {@code 1} and {@code 32} (inclusive), then that many low-order
165 >     * bits of the returned value will be (approximately) independently
166 >     * chosen bit values, each of which is (approximately) equally
167 >     * likely to be {@code 0} or {@code 1}. The method {@code next} is
168 >     * implemented by class {@code Random} by atomically updating the seed to
169 >     *  <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
170 >     * and returning
171 >     *  <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
172 >     *
173 >     * This is a linear congruential pseudorandom number generator, as
174 >     * defined by D. H. Lehmer and described by Donald E. Knuth in
175 >     * <i>The Art of Computer Programming,</i> Volume 3:
176 >     * <i>Seminumerical Algorithms</i>, section 3.2.1.
177 >     *
178 >     * @param  bits random bits
179 >     * @return the next pseudorandom value from this random number
180 >     *         generator's sequence
181 >     * @since  1.1
182       */
183      protected int next(int bits) {
184          long oldseed, nextseed;
185 +        AtomicLong seed = this.seed;
186          do {
187 <          oldseed = seed.get();
188 <          nextseed = (oldseed * multiplier + addend) & mask;
187 >            oldseed = seed.get();
188 >            nextseed = (oldseed * multiplier + addend) & mask;
189          } while (!seed.compareAndSet(oldseed, nextseed));
190          return (int)(nextseed >>> (48 - bits));
191      }
192  
144    private static final int BITS_PER_BYTE = 8;
145    private static final int BYTES_PER_INT = 4;
146
193      /**
194 <     * Generates random bytes and places them into a user-supplied
195 <     * byte array.  The number of random bytes produced is equal to
194 >     * Generates random bytes and places them into a user-supplied
195 >     * byte array.  The number of random bytes produced is equal to
196       * the length of the byte array.
197 <     *
198 <     * @param bytes  the non-null byte array in which to put the
199 <     *               random bytes.
200 <     * @since   JDK1.1
197 >     *
198 >     * <p>The method {@code nextBytes} is implemented by class {@code Random}
199 >     * as if by:
200 >     *  <pre> {@code
201 >     * public void nextBytes(byte[] bytes) {
202 >     *   for (int i = 0; i < bytes.length; )
203 >     *     for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
204 >     *          n-- > 0; rnd >>= 8)
205 >     *       bytes[i++] = (byte)rnd;
206 >     * }}</pre>
207 >     *
208 >     * @param  bytes the byte array to fill with random bytes
209 >     * @throws NullPointerException if the byte array is null
210 >     * @since  1.1
211       */
212      public void nextBytes(byte[] bytes) {
213 <        int numRequested = bytes.length;
214 <
215 <        int numGot = 0, rnd = 0;
216 <
217 <        while (true) {
162 <            for (int i = 0; i < BYTES_PER_INT; i++) {
163 <                if (numGot == numRequested)
164 <                    return;
165 <
166 <                rnd = (i==0 ? next(BITS_PER_BYTE * BYTES_PER_INT)
167 <                            : rnd >> BITS_PER_BYTE);
168 <                bytes[numGot++] = (byte)rnd;
169 <            }
170 <        }
213 >        for (int i = 0, len = bytes.length; i < len; )
214 >            for (int rnd = nextInt(),
215 >                     n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
216 >                 n-- > 0; rnd >>= Byte.SIZE)
217 >                bytes[i++] = (byte)rnd;
218      }
219  
220      /**
221 <     * Returns the next pseudorandom, uniformly distributed <code>int</code>
222 <     * value from this random number generator's sequence. The general
223 <     * contract of <tt>nextInt</tt> is that one <tt>int</tt> value is
221 >     * Returns the next pseudorandom, uniformly distributed {@code int}
222 >     * value from this random number generator's sequence. The general
223 >     * contract of {@code nextInt} is that one {@code int} value is
224       * pseudorandomly generated and returned. All 2<font size="-1"><sup>32
225 <     * </sup></font> possible <tt>int</tt> values are produced with
226 <     * (approximately) equal probability. The method <tt>nextInt</tt> is
227 <     * implemented by class <tt>Random</tt> as follows:
228 <     * <blockquote><pre>
229 <     * public int nextInt() {  return next(32); }</pre></blockquote>
225 >     * </sup></font> possible {@code int} values are produced with
226 >     * (approximately) equal probability.
227 >     *
228 >     * <p>The method {@code nextInt} is implemented by class {@code Random}
229 >     * as if by:
230 >     *  <pre> {@code
231 >     * public int nextInt() {
232 >     *   return next(32);
233 >     * }}</pre>
234       *
235 <     * @return  the next pseudorandom, uniformly distributed <code>int</code>
236 <     *          value from this random number generator's sequence.
235 >     * @return the next pseudorandom, uniformly distributed {@code int}
236 >     *         value from this random number generator's sequence
237       */
238 <    public int nextInt() {  return next(32); }
238 >    public int nextInt() {
239 >        return next(32);
240 >    }
241  
242      /**
243 <     * Returns a pseudorandom, uniformly distributed <tt>int</tt> value
243 >     * Returns a pseudorandom, uniformly distributed {@code int} value
244       * between 0 (inclusive) and the specified value (exclusive), drawn from
245       * this random number generator's sequence.  The general contract of
246 <     * <tt>nextInt</tt> is that one <tt>int</tt> value in the specified range
247 <     * is pseudorandomly generated and returned.  All <tt>n</tt> possible
248 <     * <tt>int</tt> values are produced with (approximately) equal
249 <     * probability.  The method <tt>nextInt(int n)</tt> is implemented by
250 <     * class <tt>Random</tt> as follows:
251 <     * <blockquote><pre>
246 >     * {@code nextInt} is that one {@code int} value in the specified range
247 >     * is pseudorandomly generated and returned.  All {@code n} possible
248 >     * {@code int} values are produced with (approximately) equal
249 >     * probability.  The method {@code nextInt(int n)} is implemented by
250 >     * class {@code Random} as if by:
251 >     *  <pre> {@code
252       * public int nextInt(int n) {
253 <     *     if (n<=0)
254 <     *          throw new IllegalArgumentException("n must be positive");
253 >     *   if (n <= 0)
254 >     *     throw new IllegalArgumentException("n must be positive");
255       *
256 <     *     if ((n & -n) == n)  // i.e., n is a power of 2
257 <     *         return (int)((n * (long)next(31)) >> 31);
256 >     *   if ((n & -n) == n)  // i.e., n is a power of 2
257 >     *     return (int)((n * (long)next(31)) >> 31);
258       *
259 <     *     int bits, val;
260 <     *     do {
261 <     *         bits = next(31);
262 <     *         val = bits % n;
263 <     *     } while(bits - val + (n-1) < 0);
264 <     *     return val;
265 <     * }
266 <     * </pre></blockquote>
267 <     * <p>
215 <     * The hedge "approximately" is used in the foregoing description only
259 >     *   int bits, val;
260 >     *   do {
261 >     *       bits = next(31);
262 >     *       val = bits % n;
263 >     *   } while (bits - val + (n-1) < 0);
264 >     *   return val;
265 >     * }}</pre>
266 >     *
267 >     * <p>The hedge "approximately" is used in the foregoing description only
268       * because the next method is only approximately an unbiased source of
269 <     * independently chosen bits.  If it were a perfect source of randomly
270 <     * chosen bits, then the algorithm shown would choose <tt>int</tt>
269 >     * independently chosen bits.  If it were a perfect source of randomly
270 >     * chosen bits, then the algorithm shown would choose {@code int}
271       * values from the stated range with perfect uniformity.
272       * <p>
273       * The algorithm is slightly tricky.  It rejects values that would result
# Line 235 | Line 287 | class Random implements java.io.Serializ
287       * successive calls to this method if n is a small power of two.
288       *
289       * @param n the bound on the random number to be returned.  Must be
290 <     *        positive.
291 <     * @return  a pseudorandom, uniformly distributed <tt>int</tt>
292 <     *          value between 0 (inclusive) and n (exclusive).
293 <     * @exception IllegalArgumentException n is not positive.
290 >     *        positive.
291 >     * @return the next pseudorandom, uniformly distributed {@code int}
292 >     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
293 >     *         from this random number generator's sequence
294 >     * @throws IllegalArgumentException if n is not positive
295       * @since 1.2
296       */
297  
298      public int nextInt(int n) {
299 <        if (n<=0)
299 >        if (n <= 0)
300              throw new IllegalArgumentException("n must be positive");
301  
302          if ((n & -n) == n)  // i.e., n is a power of 2
# Line 253 | Line 306 | class Random implements java.io.Serializ
306          do {
307              bits = next(31);
308              val = bits % n;
309 <        } while(bits - val + (n-1) < 0);
309 >        } while (bits - val + (n-1) < 0);
310          return val;
311      }
312  
313      /**
314 <     * Returns the next pseudorandom, uniformly distributed <code>long</code>
315 <     * value from this random number generator's sequence. The general
316 <     * contract of <tt>nextLong</tt> is that one long value is pseudorandomly
317 <     * generated and returned. All 2<font size="-1"><sup>64</sup></font>
318 <     * possible <tt>long</tt> values are produced with (approximately) equal
319 <     * probability. The method <tt>nextLong</tt> is implemented by class
320 <     * <tt>Random</tt> as follows:
321 <     * <blockquote><pre>
314 >     * Returns the next pseudorandom, uniformly distributed {@code long}
315 >     * value from this random number generator's sequence. The general
316 >     * contract of {@code nextLong} is that one {@code long} value is
317 >     * pseudorandomly generated and returned.
318 >     *
319 >     * <p>The method {@code nextLong} is implemented by class {@code Random}
320 >     * as if by:
321 >     *  <pre> {@code
322       * public long nextLong() {
323 <     *       return ((long)next(32) << 32) + next(32);
324 <     * }</pre></blockquote>
323 >     *   return ((long)next(32) << 32) + next(32);
324 >     * }}</pre>
325 >     *
326 >     * Because class {@code Random} uses a seed with only 48 bits,
327 >     * this algorithm will not return all possible {@code long} values.
328       *
329 <     * @return  the next pseudorandom, uniformly distributed <code>long</code>
330 <     *          value from this random number generator's sequence.
329 >     * @return the next pseudorandom, uniformly distributed {@code long}
330 >     *         value from this random number generator's sequence
331       */
332      public long nextLong() {
333          // it's okay that the bottom word remains signed.
# Line 280 | Line 336 | class Random implements java.io.Serializ
336  
337      /**
338       * Returns the next pseudorandom, uniformly distributed
339 <     * <code>boolean</code> value from this random number generator's
340 <     * sequence. The general contract of <tt>nextBoolean</tt> is that one
341 <     * <tt>boolean</tt> value is pseudorandomly generated and returned.  The
342 <     * values <code>true</code> and <code>false</code> are produced with
343 <     * (approximately) equal probability. The method <tt>nextBoolean</tt> is
344 <     * implemented by class <tt>Random</tt> as follows:
345 <     * <blockquote><pre>
346 <     * public boolean nextBoolean() {return next(1) != 0;}
347 <     * </pre></blockquote>
348 <     * @return  the next pseudorandom, uniformly distributed
349 <     *          <code>boolean</code> value from this random number generator's
350 <     *          sequence.
339 >     * {@code boolean} value from this random number generator's
340 >     * sequence. The general contract of {@code nextBoolean} is that one
341 >     * {@code boolean} value is pseudorandomly generated and returned.  The
342 >     * values {@code true} and {@code false} are produced with
343 >     * (approximately) equal probability.
344 >     *
345 >     * <p>The method {@code nextBoolean} is implemented by class {@code Random}
346 >     * as if by:
347 >     *  <pre> {@code
348 >     * public boolean nextBoolean() {
349 >     *   return next(1) != 0;
350 >     * }}</pre>
351 >     *
352 >     * @return the next pseudorandom, uniformly distributed
353 >     *         {@code boolean} value from this random number generator's
354 >     *         sequence
355       * @since 1.2
356       */
357 <    public boolean nextBoolean() {return next(1) != 0;}
357 >    public boolean nextBoolean() {
358 >        return next(1) != 0;
359 >    }
360  
361      /**
362 <     * Returns the next pseudorandom, uniformly distributed <code>float</code>
363 <     * value between <code>0.0</code> and <code>1.0</code> from this random
364 <     * number generator's sequence. <p>
365 <     * The general contract of <tt>nextFloat</tt> is that one <tt>float</tt>
366 <     * value, chosen (approximately) uniformly from the range <tt>0.0f</tt>
367 <     * (inclusive) to <tt>1.0f</tt> (exclusive), is pseudorandomly
368 <     * generated and returned. All 2<font size="-1"><sup>24</sup></font>
369 <     * possible <tt>float</tt> values of the form
370 <     * <i>m&nbsp;x&nbsp</i>2<font size="-1"><sup>-24</sup></font>, where
371 <     * <i>m</i> is a positive integer less than 2<font size="-1"><sup>24</sup>
372 <     * </font>, are produced with (approximately) equal probability. The
373 <     * method <tt>nextFloat</tt> is implemented by class <tt>Random</tt> as
374 <     * follows:
375 <     * <blockquote><pre>
362 >     * Returns the next pseudorandom, uniformly distributed {@code float}
363 >     * value between {@code 0.0} and {@code 1.0} from this random
364 >     * number generator's sequence.
365 >     *
366 >     * <p>The general contract of {@code nextFloat} is that one
367 >     * {@code float} value, chosen (approximately) uniformly from the
368 >     * range {@code 0.0f} (inclusive) to {@code 1.0f} (exclusive), is
369 >     * pseudorandomly generated and returned. All 2<font
370 >     * size="-1"><sup>24</sup></font> possible {@code float} values
371 >     * of the form <i>m&nbsp;x&nbsp</i>2<font
372 >     * size="-1"><sup>-24</sup></font>, where <i>m</i> is a positive
373 >     * integer less than 2<font size="-1"><sup>24</sup> </font>, are
374 >     * produced with (approximately) equal probability.
375 >     *
376 >     * <p>The method {@code nextFloat} is implemented by class {@code Random}
377 >     * as if by:
378 >     *  <pre> {@code
379       * public float nextFloat() {
380 <     *      return next(24) / ((float)(1 << 24));
381 <     * }</pre></blockquote>
382 <     * The hedge "approximately" is used in the foregoing description only
383 <     * because the next method is only approximately an unbiased source of
384 <     * independently chosen bits. If it were a perfect source or randomly
385 <     * chosen bits, then the algorithm shown would choose <tt>float</tt>
380 >     *   return next(24) / ((float)(1 << 24));
381 >     * }}</pre>
382 >     *
383 >     * <p>The hedge "approximately" is used in the foregoing description only
384 >     * because the next method is only approximately an unbiased source of
385 >     * independently chosen bits. If it were a perfect source of randomly
386 >     * chosen bits, then the algorithm shown would choose {@code float}
387       * values from the stated range with perfect uniformity.<p>
388       * [In early versions of Java, the result was incorrectly calculated as:
389 <     * <blockquote><pre>
390 <     * return next(30) / ((float)(1 << 30));</pre></blockquote>
391 <     * This might seem to be equivalent, if not better, but in fact it
392 <     * introduced a slight nonuniformity because of the bias in the rounding
393 <     * of floating-point numbers: it was slightly more likely that the
394 <     * low-order bit of the significand would be 0 than that it would be 1.]
395 <     *
396 <     * @return  the next pseudorandom, uniformly distributed <code>float</code>
397 <     *          value between <code>0.0</code> and <code>1.0</code> from this
398 <     *          random number generator's sequence.
389 >     *  <pre> {@code
390 >     *   return next(30) / ((float)(1 << 30));}</pre>
391 >     * This might seem to be equivalent, if not better, but in fact it
392 >     * introduced a slight nonuniformity because of the bias in the rounding
393 >     * of floating-point numbers: it was slightly more likely that the
394 >     * low-order bit of the significand would be 0 than that it would be 1.]
395 >     *
396 >     * @return the next pseudorandom, uniformly distributed {@code float}
397 >     *         value between {@code 0.0} and {@code 1.0} from this
398 >     *         random number generator's sequence
399       */
400      public float nextFloat() {
401 <        int i = next(24);
336 <        return i / ((float)(1 << 24));
401 >        return next(24) / ((float)(1 << 24));
402      }
403  
404      /**
405 <     * Returns the next pseudorandom, uniformly distributed
406 <     * <code>double</code> value between <code>0.0</code> and
407 <     * <code>1.0</code> from this random number generator's sequence. <p>
408 <     * The general contract of <tt>nextDouble</tt> is that one
409 <     * <tt>double</tt> value, chosen (approximately) uniformly from the
410 <     * range <tt>0.0d</tt> (inclusive) to <tt>1.0d</tt> (exclusive), is
411 <     * pseudorandomly generated and returned. All
412 <     * 2<font size="-1"><sup>53</sup></font> possible <tt>float</tt>
413 <     * values of the form <i>m&nbsp;x&nbsp;</i>2<font size="-1"><sup>-53</sup>
414 <     * </font>, where <i>m</i> is a positive integer less than
415 <     * 2<font size="-1"><sup>53</sup></font>, are produced with
416 <     * (approximately) equal probability. The method <tt>nextDouble</tt> is
352 <     * implemented by class <tt>Random</tt> as follows:
353 <     * <blockquote><pre>
405 >     * Returns the next pseudorandom, uniformly distributed
406 >     * {@code double} value between {@code 0.0} and
407 >     * {@code 1.0} from this random number generator's sequence.
408 >     *
409 >     * <p>The general contract of {@code nextDouble} is that one
410 >     * {@code double} value, chosen (approximately) uniformly from the
411 >     * range {@code 0.0d} (inclusive) to {@code 1.0d} (exclusive), is
412 >     * pseudorandomly generated and returned.
413 >     *
414 >     * <p>The method {@code nextDouble} is implemented by class {@code Random}
415 >     * as if by:
416 >     *  <pre> {@code
417       * public double nextDouble() {
418 <     *       return (((long)next(26) << 27) + next(27))
419 <     *           / (double)(1L << 53);
420 <     * }</pre></blockquote><p>
421 <     * The hedge "approximately" is used in the foregoing description only
422 <     * because the <tt>next</tt> method is only approximately an unbiased
423 <     * source of independently chosen bits. If it were a perfect source or
424 <     * randomly chosen bits, then the algorithm shown would choose
425 <     * <tt>double</tt> values from the stated range with perfect uniformity.
418 >     *   return (((long)next(26) << 27) + next(27))
419 >     *     / (double)(1L << 53);
420 >     * }}</pre>
421 >     *
422 >     * <p>The hedge "approximately" is used in the foregoing description only
423 >     * because the {@code next} method is only approximately an unbiased
424 >     * source of independently chosen bits. If it were a perfect source of
425 >     * randomly chosen bits, then the algorithm shown would choose
426 >     * {@code double} values from the stated range with perfect uniformity.
427       * <p>[In early versions of Java, the result was incorrectly calculated as:
428 <     * <blockquote><pre>
429 <     *  return (((long)next(27) << 27) + next(27))
430 <     *      / (double)(1L << 54);</pre></blockquote>
431 <     * This might seem to be equivalent, if not better, but in fact it
432 <     * introduced a large nonuniformity because of the bias in the rounding
433 <     * of floating-point numbers: it was three times as likely that the
434 <     * low-order bit of the significand would be 0 than that it would be
435 <     * 1! This nonuniformity probably doesn't matter much in practice, but
436 <     * we strive for perfection.]
437 <     *
438 <     * @return  the next pseudorandom, uniformly distributed
439 <     *          <code>double</code> value between <code>0.0</code> and
440 <     *          <code>1.0</code> from this random number generator's sequence.
428 >     *  <pre> {@code
429 >     *   return (((long)next(27) << 27) + next(27))
430 >     *     / (double)(1L << 54);}</pre>
431 >     * This might seem to be equivalent, if not better, but in fact it
432 >     * introduced a large nonuniformity because of the bias in the rounding
433 >     * of floating-point numbers: it was three times as likely that the
434 >     * low-order bit of the significand would be 0 than that it would be 1!
435 >     * This nonuniformity probably doesn't matter much in practice, but we
436 >     * strive for perfection.]
437 >     *
438 >     * @return the next pseudorandom, uniformly distributed {@code double}
439 >     *         value between {@code 0.0} and {@code 1.0} from this
440 >     *         random number generator's sequence
441 >     * @see Math#random
442       */
443      public double nextDouble() {
444 <        long l = ((long)(next(26)) << 27) + next(27);
445 <        return l / (double)(1L << 53);
444 >        return (((long)(next(26)) << 27) + next(27))
445 >            / (double)(1L << 53);
446      }
447  
448      private double nextNextGaussian;
# Line 385 | Line 450 | class Random implements java.io.Serializ
450  
451      /**
452       * Returns the next pseudorandom, Gaussian ("normally") distributed
453 <     * <code>double</code> value with mean <code>0.0</code> and standard
454 <     * deviation <code>1.0</code> from this random number generator's sequence.
453 >     * {@code double} value with mean {@code 0.0} and standard
454 >     * deviation {@code 1.0} from this random number generator's sequence.
455       * <p>
456 <     * The general contract of <tt>nextGaussian</tt> is that one
457 <     * <tt>double</tt> value, chosen from (approximately) the usual
458 <     * normal distribution with mean <tt>0.0</tt> and standard deviation
459 <     * <tt>1.0</tt>, is pseudorandomly generated and returned. The method
460 <     * <tt>nextGaussian</tt> is implemented by class <tt>Random</tt> as follows:
461 <     * <blockquote><pre>
462 <     * synchronized public double nextGaussian() {
463 <     *    if (haveNextNextGaussian) {
464 <     *            haveNextNextGaussian = false;
465 <     *            return nextNextGaussian;
466 <     *    } else {
467 <     *            double v1, v2, s;
468 <     *            do {
469 <     *                    v1 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
470 <     *                    v2 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
471 <     *                    s = v1 * v1 + v2 * v2;
472 <     *            } while (s >= 1 || s == 0);
473 <     *            double multiplier = Math.sqrt(-2 * Math.log(s)/s);
474 <     *            nextNextGaussian = v2 * multiplier;
475 <     *            haveNextNextGaussian = true;
476 <     *            return v1 * multiplier;
477 <     *    }
478 <     * }</pre></blockquote>
479 <     * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
480 <     * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
481 <     * Computer Programming</i>, Volume 2: <i>Seminumerical Algorithms</i>,
456 >     * The general contract of {@code nextGaussian} is that one
457 >     * {@code double} value, chosen from (approximately) the usual
458 >     * normal distribution with mean {@code 0.0} and standard deviation
459 >     * {@code 1.0}, is pseudorandomly generated and returned.
460 >     *
461 >     * <p>The method {@code nextGaussian} is implemented by class
462 >     * {@code Random} as if by a threadsafe version of the following:
463 >     *  <pre> {@code
464 >     * private double nextNextGaussian;
465 >     * private boolean haveNextNextGaussian = false;
466 >     *
467 >     * public double nextGaussian() {
468 >     *   if (haveNextNextGaussian) {
469 >     *     haveNextNextGaussian = false;
470 >     *     return nextNextGaussian;
471 >     *   } else {
472 >     *     double v1, v2, s;
473 >     *     do {
474 >     *       v1 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
475 >     *       v2 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
476 >     *       s = v1 * v1 + v2 * v2;
477 >     *     } while (s >= 1 || s == 0);
478 >     *     double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
479 >     *     nextNextGaussian = v2 * multiplier;
480 >     *     haveNextNextGaussian = true;
481 >     *     return v1 * multiplier;
482 >     *   }
483 >     * }}</pre>
484 >     * This uses the <i>polar method</i> of G. E. P. Box, M. E. Muller, and
485 >     * G. Marsaglia, as described by Donald E. Knuth in <i>The Art of
486 >     * Computer Programming</i>, Volume 3: <i>Seminumerical Algorithms</i>,
487       * section 3.4.1, subsection C, algorithm P. Note that it generates two
488 <     * independent values at the cost of only one call to <tt>Math.log</tt>
489 <     * and one call to <tt>Math.sqrt</tt>.
488 >     * independent values at the cost of only one call to {@code StrictMath.log}
489 >     * and one call to {@code StrictMath.sqrt}.
490       *
491 <     * @return  the next pseudorandom, Gaussian ("normally") distributed
492 <     *          <code>double</code> value with mean <code>0.0</code> and
493 <     *          standard deviation <code>1.0</code> from this random number
494 <     *          generator's sequence.
491 >     * @return the next pseudorandom, Gaussian ("normally") distributed
492 >     *         {@code double} value with mean {@code 0.0} and
493 >     *         standard deviation {@code 1.0} from this random number
494 >     *         generator's sequence
495       */
496      synchronized public double nextGaussian() {
497          // See Knuth, ACP, Section 3.4.1 Algorithm C.
498          if (haveNextNextGaussian) {
499 <            haveNextNextGaussian = false;
500 <            return nextNextGaussian;
501 <        } else {
499 >            haveNextNextGaussian = false;
500 >            return nextNextGaussian;
501 >        } else {
502              double v1, v2, s;
503 <            do {
503 >            do {
504                  v1 = 2 * nextDouble() - 1; // between -1 and 1
505 <                v2 = 2 * nextDouble() - 1; // between -1 and 1
505 >                v2 = 2 * nextDouble() - 1; // between -1 and 1
506                  s = v1 * v1 + v2 * v2;
507 <            } while (s >= 1 || s == 0);
508 <            double multiplier = Math.sqrt(-2 * Math.log(s)/s);
509 <            nextNextGaussian = v2 * multiplier;
510 <            haveNextNextGaussian = true;
511 <            return v1 * multiplier;
507 >            } while (s >= 1 || s == 0);
508 >            double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
509 >            nextNextGaussian = v2 * multiplier;
510 >            haveNextNextGaussian = true;
511 >            return v1 * multiplier;
512          }
513      }
514  
515      /**
516       * Serializable fields for Random.
517       *
518 <     * @serialField    seed long;
518 >     * @serialField    seed long
519       *              seed for random computations
520 <     * @serialField    nextNextGaussian double;
520 >     * @serialField    nextNextGaussian double
521       *              next Gaussian to be returned
522       * @serialField      haveNextNextGaussian boolean
523       *              nextNextGaussian is valid
# Line 456 | Line 526 | class Random implements java.io.Serializ
526          new ObjectStreamField("seed", Long.TYPE),
527          new ObjectStreamField("nextNextGaussian", Double.TYPE),
528          new ObjectStreamField("haveNextNextGaussian", Boolean.TYPE)
529 <        };
529 >    };
530  
531      /**
532 <     * Reconstitute the <tt>Random</tt> instance from a stream (that is,
533 <     * deserialize it). The seed is read in as long for
464 <     * historical reasons, but it is converted to an AtomicLong.
532 >     * Reconstitute the {@code Random} instance from a stream (that is,
533 >     * deserialize it).
534       */
535      private void readObject(java.io.ObjectInputStream s)
536          throws java.io.IOException, ClassNotFoundException {
537  
538          ObjectInputStream.GetField fields = s.readFields();
470        long seedVal;
539  
540 <        seedVal = (long) fields.get("seed", -1L);
540 >        // The seed is read in as {@code long} for
541 >        // historical reasons, but it is converted to an AtomicLong.
542 >        long seedVal = fields.get("seed", -1L);
543          if (seedVal < 0)
544            throw new java.io.StreamCorruptedException(
545                                "Random: invalid seed");
546 <        seed = new AtomicLong(seedVal);
546 >        resetSeed(seedVal);
547          nextNextGaussian = fields.get("nextNextGaussian", 0.0);
548          haveNextNextGaussian = fields.get("haveNextNextGaussian", false);
549      }
550  
481
551      /**
552 <     * Save the <tt>Random</tt> instance to a stream.
484 <     * The seed of a Random is serialized as a long for
485 <     * historical reasons.
486 <     *
552 >     * Save the {@code Random} instance to a stream.
553       */
554 <    synchronized private void writeObject(ObjectOutputStream s) throws IOException {
554 >    synchronized private void writeObject(ObjectOutputStream s)
555 >        throws IOException {
556 >
557          // set the values of the Serializable fields
558          ObjectOutputStream.PutField fields = s.putFields();
559 +
560 +        // The seed is serialized as a long for historical reasons.
561          fields.put("seed", seed.get());
562          fields.put("nextNextGaussian", nextNextGaussian);
563          fields.put("haveNextNextGaussian", haveNextNextGaussian);
564  
565          // save them
566          s.writeFields();
497
567      }
568  
569 < }    
569 >    // Support for resetting seed while deserializing
570 >    private static final Unsafe unsafe = Unsafe.getUnsafe();
571 >    private static final long seedOffset;
572 >    static {
573 >        try {
574 >            seedOffset = unsafe.objectFieldOffset
575 >                (Random.class.getDeclaredField("seed"));
576 >        } catch (Exception ex) { throw new Error(ex); }
577 >    }
578 >    private void resetSeed(long seedVal) {
579 >        unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal));
580 >    }
581 > }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines