[concurrency-interest] ThreadLocalRandom

Doug Lea dl at cs.oswego.edu
Tue Jan 13 07:09:38 EST 2009

Jeremy Manson wrote:
> This seems a little weirdly backwards to me (although I'm sure you had
> a good reason to do it this way).  Given that (I assume) you can't
> change the class hierarchy to add a superclass for Random, why didn't
> you extract the actual random number generation logic into a delegate
> class and have both Random and ThreadLocalRandom point to that class?

Internally, there are two small but important differences
between Random and ThreadLocalRandom:

(1) ThreadLocalRandom does not need to use locking or atomics in
the base seed update method, next(bits). Random must and does.

(2) As a heuristic (but a very noticeably effective one),
ThreadLocalRandom "protects" its cache line by adding some
padding around seed. This is more useful than you might
guess -- it counteracts tendency of garbage collectors
to relocate instances of the same class adjacently in memory,
which would otherwise cause the ThreadLocalRandoms conceptually
owned by different threads to physically interfere with each other.

But to answer your question, the reason for not
delegating the update logic is that the main pseudorandom
update step is only one line of code. It's not worth the
code bulk or performance overhead that would be needed to
encapsulate it to be usable in atomic vs direct updates etc. See


More information about the Concurrency-interest mailing list