Yishai Yishai - 6 months ago 46
Java Question

Is SecureRandom thread safe?


thread safe? That is, after initializing it, can access to the next random number be relied on to be thread safe? Examining the source code seems to show that it is, and this bug report seems to indicate that its lack of documentation as thread safe is a javadoc issue. Has anyone confirmed that it is in fact thread safe?


Yes, it is. It uses synchronization to protect the integrity of its state.

It might be possible for a provider to override the relevant methods without synchronization, but there is a lot of code out there relying on the de facto contract of thread-safe SecureRandom, so this would likely be reported as a bug.

If many threads are using a single SecureRandom, there might be contention that hurts performance. On the other hand, initializing a SecureRandom instance can be relatively slow. Whether it is best to share a global RNG, or to create a new one for each thread will depend on your application.

Update: Java 7 makes an explicit guarantee of thread-safety for Random instances. However, it also points out that contention for a single Random instance in a multi-threaded application may impair performance, and introduces the ThreadLocalRandom class as a solution.

Update 2: Java 8u112 has performance improvements by removing synchronization for java.security.SecureRandom.nextBytes(byte[] bytes)