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.16 by jsr166, Thu Feb 16 08:30:29 2006 UTC vs.
Revision 1.25 by jsr166, Wed Aug 5 01:34:23 2009 UTC

# Line 1 | Line 1
1   /*
2 < * %W% %E%
2 > * Copyright 1995-2008 Sun Microsystems, Inc.  All Rights Reserved.
3 > * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5 < * Copyright 2006 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.  Sun designates this
8 > * particular file as subject to the "Classpath" exception as provided
9 > * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 > * CA 95054 USA or visit www.sun.com if you need additional information or
23 > * have any questions.
24   */
25  
26   package java.util;
# Line 14 | Line 32 | import sun.misc.Unsafe;
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 3</i>, Section 3.2.1.)
35 > * <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
36   * <p>
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
# Line 32 | Line 50 | import sun.misc.Unsafe;
50   * <p>
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
36 * @version %I%, %G%
66   * @since   1.0
67   */
68   public
# Line 45 | 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.)
48     *
49     * @serial
77       */
78      private final AtomicLong seed;
79  
# Line 102 | Line 129 | class Random implements java.io.Serializ
129      synchronized public void setSeed(long seed) {
130          seed = (seed ^ multiplier) & mask;
131          this.seed.set(seed);
132 <        haveNextNextGaussian = false;
132 >        haveNextNextGaussian = false;
133      }
134  
135      /**
# Line 134 | Line 161 | class Random implements java.io.Serializ
161          long oldseed, nextseed;
162          AtomicLong seed = this.seed;
163          do {
164 <            oldseed = seed.get();
165 <            nextseed = (oldseed * multiplier + addend) & mask;
164 >            oldseed = seed.get();
165 >            nextseed = (oldseed * multiplier + addend) & mask;
166          } while (!seed.compareAndSet(oldseed, nextseed));
167          return (int)(nextseed >>> (48 - bits));
168      }
# Line 160 | Line 187 | class Random implements java.io.Serializ
187       * @since  1.1
188       */
189      public void nextBytes(byte[] bytes) {
190 <        for (int i = 0, len = bytes.length; i < len; )
191 <            for (int rnd = nextInt(),
192 <                     n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
193 <                 n-- > 0; rnd >>= Byte.SIZE)
194 <                bytes[i++] = (byte)rnd;
190 >        for (int i = 0, len = bytes.length; i < len; )
191 >            for (int rnd = nextInt(),
192 >                     n = Math.min(len - i, Integer.SIZE/Byte.SIZE);
193 >                 n-- > 0; rnd >>= Byte.SIZE)
194 >                bytes[i++] = (byte)rnd;
195      }
196  
197      /**
# Line 186 | Line 213 | class Random implements java.io.Serializ
213       *         value from this random number generator's sequence
214       */
215      public int nextInt() {
216 <        return next(32);
216 >        return next(32);
217      }
218  
219      /**
# Line 237 | Line 264 | class Random implements java.io.Serializ
264       * successive calls to this method if n is a small power of two.
265       *
266       * @param n the bound on the random number to be returned.  Must be
267 <     *        positive.
267 >     *        positive.
268       * @return the next pseudorandom, uniformly distributed {@code int}
269       *         value between {@code 0} (inclusive) and {@code n} (exclusive)
270       *         from this random number generator's sequence
# Line 301 | Line 328 | class Random implements java.io.Serializ
328       *
329       * @return the next pseudorandom, uniformly distributed
330       *         {@code boolean} value from this random number generator's
331 <     *         sequence
331 >     *         sequence
332       * @since 1.2
333       */
334      public boolean nextBoolean() {
335 <        return next(1) != 0;
335 >        return next(1) != 0;
336      }
337  
338      /**
# Line 392 | Line 419 | class Random implements java.io.Serializ
419       */
420      public double nextDouble() {
421          return (((long)(next(26)) << 27) + next(27))
422 <            / (double)(1L << 53);
422 >            / (double)(1L << 53);
423      }
424  
425      private double nextNextGaussian;
# Line 446 | Line 473 | class Random implements java.io.Serializ
473      synchronized public double nextGaussian() {
474          // See Knuth, ACP, Section 3.4.1 Algorithm C.
475          if (haveNextNextGaussian) {
476 <            haveNextNextGaussian = false;
477 <            return nextNextGaussian;
478 <        } else {
476 >            haveNextNextGaussian = false;
477 >            return nextNextGaussian;
478 >        } else {
479              double v1, v2, s;
480 <            do {
480 >            do {
481                  v1 = 2 * nextDouble() - 1; // between -1 and 1
482 <                v2 = 2 * nextDouble() - 1; // between -1 and 1
482 >                v2 = 2 * nextDouble() - 1; // between -1 and 1
483                  s = v1 * v1 + v2 * v2;
484 <            } while (s >= 1 || s == 0);
485 <            double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
486 <            nextNextGaussian = v2 * multiplier;
487 <            haveNextNextGaussian = true;
488 <            return v1 * multiplier;
484 >            } while (s >= 1 || s == 0);
485 >            double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
486 >            nextNextGaussian = v2 * multiplier;
487 >            haveNextNextGaussian = true;
488 >            return v1 * multiplier;
489          }
490      }
491  
492      /**
493       * Serializable fields for Random.
494       *
495 <     * @serialField    seed long;
495 >     * @serialField    seed long
496       *              seed for random computations
497 <     * @serialField    nextNextGaussian double;
497 >     * @serialField    nextNextGaussian double
498       *              next Gaussian to be returned
499       * @serialField      haveNextNextGaussian boolean
500       *              nextNextGaussian is valid
# Line 487 | Line 514 | class Random implements java.io.Serializ
514  
515          ObjectInputStream.GetField fields = s.readFields();
516  
517 <        // The seed is read in as {@code long} for
518 <        // historical reasons, but it is converted to an AtomicLong.
519 <        long seedVal = (long) fields.get("seed", -1L);
517 >        // The seed is read in as {@code long} for
518 >        // historical reasons, but it is converted to an AtomicLong.
519 >        long seedVal = fields.get("seed", -1L);
520          if (seedVal < 0)
521            throw new java.io.StreamCorruptedException(
522                                "Random: invalid seed");
# Line 502 | Line 529 | class Random implements java.io.Serializ
529       * Save the {@code Random} instance to a stream.
530       */
531      synchronized private void writeObject(ObjectOutputStream s)
532 <        throws IOException {
532 >        throws IOException {
533  
534          // set the values of the Serializable fields
535          ObjectOutputStream.PutField fields = s.putFields();
536  
537 <        // The seed is serialized as a long for historical reasons.
537 >        // The seed is serialized as a long for historical reasons.
538          fields.put("seed", seed.get());
539          fields.put("nextNextGaussian", nextNextGaussian);
540          fields.put("haveNextNextGaussian", haveNextNextGaussian);
# Line 523 | Line 550 | class Random implements java.io.Serializ
550          try {
551              seedOffset = unsafe.objectFieldOffset
552                  (Random.class.getDeclaredField("seed"));
553 <        } catch (Exception ex) { throw new Error(ex); }
553 >        } catch (Exception ex) { throw new Error(ex); }
554      }
555      private void resetSeed(long seedVal) {
556          unsafe.putObjectVolatile(this, seedOffset, new AtomicLong(seedVal));

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines