In video [1:23] Jose Paumard talks about why using ThreadLocal is evil; especially, if the code creates countless (virtual) threads.
- Can we say the same thing for ThreadLocalRandom?
- Should people use Random over ThreadLocalRandom in (virtual) threads?
- Or is it just name similarity that we should stick with ThreadLocalRandom?
Additional notes...
According to simple tests, Both Random and ThreadLocalRandom works:
public static void threadLocalRandomTest() {
enum TestType {
useNewThreadLocalRandom, useNewRandom,
ReUseThreadLocal, ReUseRandom,
ReUseGlobalRandom,
customThreadLocalRandom, customRandom
}
var testType = TestType.useNewThreadLocalRandom;
var rg = new Random();
IntStream.range(0, 1_000_000).forEach(i -> {
if (testType == TestType.useNewThreadLocalRandom) {//63mb->60mb
IntStream.range(0, 100).forEach(j -> {
ThreadLocalRandom.current().nextFloat(1);
});
}
if (testType == TestType.useNewRandom) {//326mb->323mb
IntStream.range(0, 100).forEach(j -> {
new Random().nextFloat(1);
});
}
if (testType == TestType.ReUseThreadLocal) {//65mb->61mb
var r = ThreadLocalRandom.current();
IntStream.range(0, 100).forEach(j -> {
r.nextFloat(1);
});
}
if (testType == TestType.ReUseRandom) {//111mb->108mb
var r = new Random();
IntStream.range(0, 100).forEach(j -> {
r.nextFloat(1);
});
}
if (testType == TestType.ReUseGlobalRandom) {//64mb->61mb
IntStream.range(0, 100).forEach(j -> {
rg.nextFloat(1);
});
}
});
}