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

Comparing jsr166/src/main/java/util/concurrent/ThreadLocalRandom.java (file contents):
Revision 1.6 by jsr166, Tue Mar 15 19:47:03 2011 UTC vs.
Revision 1.7 by dl, Thu Jan 10 15:03:25 2013 UTC

# Line 7 | Line 7
7   package java.util.concurrent;
8  
9   import java.util.Random;
10 + import java.util.concurrent.atomic.AtomicInteger;
11 + import java.util.concurrent.atomic.AtomicLong;
12  
13   /**
14   * A random number generator isolated to the current thread.  Like the
# Line 33 | Line 35 | import java.util.Random;
35   * @author Doug Lea
36   */
37   public class ThreadLocalRandom extends Random {
38 +    /*
39 +     * This class implements the java.util.Random API (and subclasses
40 +     * Random) using a single static instance that accesses random
41 +     * number state held in class Thread (primarily, field
42 +     * threadLocalRandomSeed). In doing so, it also provides a home
43 +     * for managing package-private utilities that rely on exactly the
44 +     * same state as needed to maintain the ThreadLocalRandom
45 +     * instances. We leverage the need for an initialization flag
46 +     * field to also use it as a "probe" -- a self-adjusting thread
47 +     * hash used for contention avoidance, as well as a secondary
48 +     * simpler (xorShift) random seed that is conservatively used to
49 +     * avoid otherwise surprising users by hijacking the
50 +     * ThreadLocalRandom sequence.  The dual use is a marriage of
51 +     * convenience, but is a simple and efficient way of reducing
52 +     * application-level overhead and footprint of most concurrent
53 +     * programs.
54 +     *
55 +     * Because this class is in a different package than class Thread,
56 +     * field access methods must use Unsafe to bypass access control
57 +     * rules.  The base functionality of Random methods is
58 +     * conveniently isolated in method next(bits), that just reads and
59 +     * writes the Thread field rather than its own field. However, to
60 +     * conform to the requirements of the Random constructor, during
61 +     * construction, the common static ThreadLocalRandom must maintain
62 +     * initialization and value fields, mainly for the sake of
63 +     * disabling user calls to setSeed while still allowing a call
64 +     * from constructor.  For serialization compatibility, these
65 +     * fields are left with the same declarations as used in the
66 +     * previous ThreadLocal-based version of this class, that used
67 +     * them differently. Note that serialization is completely
68 +     * unnecessary because there is only a static singleton. But these
69 +     * mechanics still ensure compatibility across versions.
70 +     *
71 +     * Per-instance initialization is similar to that in the no-arg
72 +     * Random constructor, but we avoid correlation among not only
73 +     * initial seeds of those created in different threads, but also
74 +     * those created using class Random itself; while at the same time
75 +     * not changing any statistical properties.  So we use the same
76 +     * underlying multiplicative sequence, but start the sequence far
77 +     * away from the base version, and then merge (xor) current time
78 +     * and per-thread probe bits to generate initial values.
79 +     *
80 +     * The nextLocalGaussian ThreadLocal supports the very rarely used
81 +     * nextGaussian method by providing a holder for the second of a
82 +     * pair of them. As is true for the base class version of this
83 +     * method, this time/space tradeoff is probably never worthwhile,
84 +     * but we provide identical statistical properties.
85 +     */
86 +
87      // same constants as Random, but must be redeclared because private
88      private static final long multiplier = 0x5DEECE66DL;
89      private static final long addend = 0xBL;
90      private static final long mask = (1L << 48) - 1;
91 +    private static final int PROBE_INCREMENT = 0x61c88647;
92  
93 <    /**
94 <     * The random seed. We can't use super.seed.
95 <     */
44 <    private long rnd;
93 >    /** Generates the basis for per-thread initial seed values */
94 >    private static final AtomicLong seedGenerator =
95 >        new AtomicLong(1269533684904616924L);
96  
97 <    /**
98 <     * Initialization flag to permit calls to setSeed to succeed only
99 <     * while executing the Random constructor.  We can't allow others
49 <     * since it would cause setting seed in one part of a program to
50 <     * unintentionally impact other usages by the thread.
51 <     */
52 <    boolean initialized;
97 >    /** Generates per-thread initialization/probe field */
98 >    private static final AtomicInteger probeGenerator =
99 >        new AtomicInteger(0xe80f8647);
100  
101 <    // Padding to help avoid memory contention among seed updates in
102 <    // different TLRs in the common case that they are located near
103 <    // each other.
57 <    private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
101 >    /** Rarely-used holder for the second of a pair of Gaussians */
102 >    private static final ThreadLocal<Double> nextLocalGaussian =
103 >        new ThreadLocal<Double>();
104  
105 <    /**
106 <     * The actual ThreadLocal
105 >    /*
106 >     * Fields used only during singleton initialization
107       */
108 <    private static final ThreadLocal<ThreadLocalRandom> localRandom =
109 <        new ThreadLocal<ThreadLocalRandom>() {
110 <            protected ThreadLocalRandom initialValue() {
111 <                return new ThreadLocalRandom();
112 <            }
113 <    };
108 >    private long rnd;    // superclass random value
109 >    boolean initialized; // true when constructor completes
110 >
111 >    /** Constructor used only for static singleton */
112 >    private ThreadLocalRandom() {
113 >        initialized = true; // false during super() call
114 >    }
115  
116 +    /** The common ThreadLocalRandom */
117 +    static final ThreadLocalRandom instance = new ThreadLocalRandom();
118  
119      /**
120 <     * Constructor called only by localRandom.initialValue.
121 <     */
122 <    ThreadLocalRandom() {
123 <        super();
124 <        initialized = true;
120 >     * Initialize Thread fields for the current thread.  Called only
121 >     * when Thread.threadLocalRandomProbe is zero, indicating that a
122 >     * thread local seed value needs to be generated. Note that even
123 >     * though the initialization is purely thread-local, we need to
124 >     * rely on (static) atomic generators to initialize the values.
125 >     */
126 >    static final void localInit() {
127 >        int p = probeGenerator.getAndAdd(PROBE_INCREMENT);
128 >        int probe = (p == 0) ? 1 : p; // skip 0
129 >        long current, next;
130 >        do { // same sequence as j.u.Random but different initial value
131 >            current = seedGenerator.get();
132 >            next = current * 181783497276652981L;
133 >        } while (!seedGenerator.compareAndSet(current, next));
134 >        long r = next ^ ((long)probe << 32) ^ System.nanoTime();
135 >        Thread t = Thread.currentThread();
136 >        UNSAFE.putLong(t, SEED, r);
137 >        UNSAFE.putInt(t, PROBE, probe);
138      }
139  
140      /**
# Line 81 | Line 143 | public class ThreadLocalRandom extends R
143       * @return the current thread's {@code ThreadLocalRandom}
144       */
145      public static ThreadLocalRandom current() {
146 <        return localRandom.get();
146 >        if (UNSAFE.getInt(Thread.currentThread(), PROBE) == 0)
147 >            localInit();
148 >        return instance;
149      }
150  
151      /**
# Line 91 | Line 155 | public class ThreadLocalRandom extends R
155       * @throws UnsupportedOperationException always
156       */
157      public void setSeed(long seed) {
158 <        if (initialized)
158 >        if (initialized) // allow call from super() constructor
159              throw new UnsupportedOperationException();
96        rnd = (seed ^ multiplier) & mask;
160      }
161  
162      protected int next(int bits) {
163 <        rnd = (rnd * multiplier + addend) & mask;
164 <        return (int) (rnd >>> (48-bits));
163 >        Thread t; long r; // read and update per-thread seed
164 >        UNSAFE.putLong
165 >            (t = Thread.currentThread(), SEED,
166 >             r = (UNSAFE.getLong(t, SEED) * multiplier + addend) & mask);
167 >        return (int) (r >>> (48-bits));
168      }
169  
170      /**
# Line 193 | Line 259 | public class ThreadLocalRandom extends R
259          return nextDouble() * (bound - least) + least;
260      }
261  
262 +    public double nextGaussian() {
263 +        // Use nextLocalGaussian instead of nextGaussian field
264 +        Double d = nextLocalGaussian.get();
265 +        if (d != null) {
266 +            nextLocalGaussian.set(null);
267 +            return d.doubleValue();
268 +        }
269 +        double v1, v2, s;
270 +        do {
271 +            v1 = 2 * nextDouble() - 1; // between -1 and 1
272 +            v2 = 2 * nextDouble() - 1; // between -1 and 1
273 +            s = v1 * v1 + v2 * v2;
274 +        } while (s >= 1 || s == 0);
275 +        double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
276 +        nextLocalGaussian.set(new Double(v2 * multiplier));
277 +        return v1 * multiplier;
278 +    }
279 +
280 +    // Within-package utilities
281 +
282 +    /*
283 +     * Descriptions of the usages of the methods below can be found in
284 +     * the classes that use them. Briefly, a thread's "probe" value is
285 +     * a non-zero hash code that (probably) does not collide with
286 +     * other existing threads with respect to any power of two
287 +     * collision space. When it does collide, it is pseudo-randomly
288 +     * adjusted (using a Marsaglia XorShift). The nextSecondarySeed
289 +     * method is used in the same contexts as ThreadLocalRandom, but
290 +     * only for transient usages such as random adaptive spin/block
291 +     * sequences for which a cheap RNG suffices and for which it could
292 +     * in principle disrupt user-visible statistical properties of the
293 +     * main ThreadLocalRandom if we were to use it.
294 +     *
295 +     * Note: Because of package-protection issues, versions of some
296 +     * these methods also appear in some subpackage classes.
297 +     */
298 +
299 +    /**
300 +     * Returns the probe value for the current thread without forcing
301 +     * initialization. Note that invoking ThreadLocalRandom.current()
302 +     * can be used to force initialization on zero return.
303 +     */
304 +    static final int getProbe() {
305 +        return UNSAFE.getInt(Thread.currentThread(), PROBE);
306 +    }
307 +
308 +    /**
309 +     * Pseudo-randomly advances and records the given probe value for the
310 +     * given thread.
311 +     */
312 +    static final int advanceProbe(int probe) {
313 +        probe ^= probe << 13;   // xorshift
314 +        probe ^= probe >>> 17;
315 +        probe ^= probe << 5;
316 +        UNSAFE.putInt(Thread.currentThread(), PROBE, probe);
317 +        return probe;
318 +    }
319 +
320 +    /**
321 +     * Returns the pseudo-randomly initialized or updated secondary seed.
322 +     */
323 +    static final int nextSecondarySeed() {
324 +        int r;
325 +        Thread t = Thread.currentThread();
326 +        if ((r = UNSAFE.getInt(t, SECONDARY)) != 0) {
327 +            r ^= r << 13;   // xorshift
328 +            r ^= r >>> 17;
329 +            r ^= r << 5;
330 +        }
331 +        else if ((r = (int)UNSAFE.getLong(t, SEED)) == 0)
332 +            r = 1; // avoid zero
333 +        UNSAFE.putInt(t, SECONDARY, r);
334 +        return r;
335 +    }
336 +
337      private static final long serialVersionUID = -5851777807851030925L;
338 +
339 +    // Unsafe mechanics
340 +    private static final sun.misc.Unsafe UNSAFE;
341 +    private static final long SEED;
342 +    private static final long PROBE;
343 +    private static final long SECONDARY;
344 +    static {
345 +        try {
346 +            UNSAFE = sun.misc.Unsafe.getUnsafe();
347 +            Class<?> tk = Thread.class;
348 +            SEED = UNSAFE.objectFieldOffset
349 +                (tk.getDeclaredField("threadLocalRandomSeed"));
350 +            PROBE = UNSAFE.objectFieldOffset
351 +                (tk.getDeclaredField("threadLocalRandomProbe"));
352 +            SECONDARY = UNSAFE.objectFieldOffset
353 +                (tk.getDeclaredField("threadLocalRandomSecondarySeed"));
354 +        } catch (Exception e) {
355 +            throw new Error(e);
356 +        }
357 +    }
358   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines