Improving ThreadLocalRandom (and related classes)

Chris Hegarty chris.hegarty at
Tue Jan 8 16:07:10 UTC 2013


I have no objection as such to adding certain fields to j.l.Thread to 
support faster ThreadLocalRandom. Maybe it would help to see how they 
are to be used?

Given, 1 and 2 below ( I'm not sure about 3 ), would having a direct 
reference from j.l.Thread to ThreadLocalRandom (rather than using 
ThreadLocal) resolve these problems?


On 01/08/2013 12:05 PM, Doug Lea wrote:
> When we introduced ThreadLocalRandom, we conservatively
> implemented it to use an actual ThreadLocal. However,
> as it becomes more widely used, it is worth improving
> the implementation by housing ThreadLocalRandom state
> (and related bookkeeping) in class Thread itself.
> This would entail three fields (16 total bytes).
> So I propose adding the following to class Thread:
>    // The following three initially uninitialized fields are exclusively
>    // managed by class java.util.concurrent.ThreadLocalRandom.
>    /** The current seed for a ThreadLocalRandom */
>    long threadLocalRandomSeed;
>    /** Probe hash value; nonzero if threadLocalRandomSeed initialized */
>    int threadLocalRandomProbe;
>    /** Secondary seed isolated from public ThreadLocalRandom sequence */
>    int threadLocalRandomSecondarySeed;
> The reasons for doing it in this way are:
> 1. Uniformly faster access to ThreadLocalRandom state. While
> ThreadLocal access is normally pretty fast already, this is
> not only faster, it does not degrade in cases where user
> programs create large numbers of ThreadLocals, which
> may (probabilistically) cause any given access to become
> slower.
> 2. Smaller total footprint for any program using ThreadLocalRandom.
> Three fields require less space than boxing into a padded
> ThreadLocal object. As ThreadLocalRandom becomes widely used
> within JDK itself, this includes just about all programs.
> 3. Further time/space savings for java.util.concurrent ForkJoinPool,
> ConcurrentHashMap, LongAdder, ConcurrentSkipList, and other
> classes that could use this form of the unified ThreadLocalRandom
> bookkeeping rather than their own special-purpose ThreadLocals
> as they now do.
> Any objections? If not, I'd need the help of someone permitted to
> paste the above into class Thread, review, and and commit.
> -Doug

More information about the core-libs-dev mailing list