-
Notifications
You must be signed in to change notification settings - Fork 12.6k
Description
Describe the bug
Using the global scala.util.Random singleton causes a severe performance bottleneck in multi-threaded applications. All threads must wait their turn for a single, shared lock to generate a random number, creating a "traffic jam" that slows the entire application down.
To Reproduce
Steps to reproduce the behavior:
- Identify code that uses
scala.util.Randomin a path that is called by many concurrent threads (e.g., a web request handler). - Use a load testing tool to send hundreds of concurrent requests to that code path.
- Use a JVM profiler to monitor the application's threads.
- See that many threads are in a
BLOCKEDstate, waiting on a lock forjava.util.Random.
Expected behavior
The application should scale and handle many concurrent requests efficiently, without being slowed down by random number generation.
Screenshots
N/A. This is a performance issue observable in a profiler, not a visual UI error.
Environment
- Language: Scala (2.12, 2.13+)
- Platform: Any modern JVM (JDK 8+)
- Context: Most noticeable in multi-threaded server applications (web services, APIs, data pipelines).
Additional context
The solution is to replace the slow, global scala.util.Random with java.util.concurrent.ThreadLocalRandom, which gives each thread its own random number generator and eliminates the bottleneck.