Using ThreadLocalRandom for random number generation

ThreadLocalRandom introduced in Java 7 is a faster way to generate random numbers, even in single threaded situations. Although it won’t make or break a game’s performance, we do enough random number generation that it’s worth taking a look at.

A couple of articles:
How to write really fast Java code
Prefer ThreadLocalRandom over Random (reddit discussion)

Note that if you do some googling around you may find some articles pointing to a bug where the same numbers are generated each time but it appears to have been fixed.

It was working as designed; they just tailored it to the assumptions people make.

If you’re concerned about speed: use your own. If you’re concerned about quality: use your own. If you’re concerned about quality: then it’s likely you worry too much. If you’re concerned about deterministic results: use your own.

Never call the same generator from more than one thread (there are exceptions to this, but it’s a very good rule of thumb). So, ThreadLocalRandom is a better choice than Random directly or indirectly through Math…and is a reasonable choice if you don’t want to use your own.

^^^ You missed one…
If you’re not using Java 7: use your own.


Is it faster for Java 6 also or only Java 7? Last time I looked at the code it looked like Java (6) implemented Random without thread-safety, so I don’t know how single threaded applications would work better if that’s the reference.

Atomic ops are thread safe. synchronized should be avoided IHMO.