Does ThreadLocalRandom proper to use in VirtualThread in Java Loom
Asked Answered
T

0

6

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);
                });
            }
        });
    }
Tantalite answered 6/10, 2022 at 22:18 Comment(1)
Related (not intended to answer this question): #15765899Borstal

© 2022 - 2025 — McMap. All rights reserved.