Yes, Java ThreadLocalRandom is Safe to Use with Virtual Threads

Because Java 21 virtual threads are very cheap — per JEP Cafe, they are about 1,000 times faster to launch than a platform thread, and use about 1,000 times less memory than a platform thread — they should never be pooled. As a result, ThreadLocal variables are unlikely to be useful in applications that use virtual threads for concurrent processing. If each task lives in its own dedicated thread, then each call to ThreadLocal ends up returning a new value, and it ends up being a factory instead of a pool! So using ThreadLocal in virtual threads is an anti-pattern. Developers should use another technique for pooling objects, such as structured concurrency, instead.

But what about ThreadLocalRandom? Is this dedicated class for providing sources of randomness to threads safe to use with virtual threads?

The short answer is: Yes, ThreadLocalRandom is safe to use with virtual threads. ThreadLocalRandom is tightly integrated with the Thread class to ensure that it remains efficient, even for virtual threads. For more information, keep reading.

Continue reading “Yes, Java ThreadLocalRandom is Safe to Use with Virtual Threads”