Home » Java » Is SecureRandom thread safe?

Is SecureRandom thread safe?

Posted by: admin November 30, 2017 Leave a comment

Questions:

Is SecureRandom 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?

Answers:

Yes, it is. It extends Random, which was always had a de facto threadsafe implementation, and, from Java 7, explicitly guarantees threadsafety.

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. The ThreadLocalRandom class could be used as a pattern to provide a solution that supports SecureRandom.

Questions:
Answers:

The current implementation of SecureRandom is thread safe, specifically the two mutating methods nextBytes(bytes[]) and setSeed(byte[]) are synchronized.

Well, as far as I’ve been able to tell, all mutating methods are eventually routed through those two methods, and SecureRandom overrides a few methods in Random to ensure that. Which works but could be brittle if the implementation is changed in the future.

The best solution is to manually synchronize on the SecureRandom instance first. This means each call stack will acquire two locks on the same object, but that is usually very cheap on modern JVMs. That is, there is not much harm in explicitly synchronizing yourself. For example:

    SecureRandom rnd = ...;

    byte[] b = new byte[NRANDOM_BYTES];
    synchronized (rnd) {
        rnd.nextBytes(b);
    }

Questions:
Answers:

Yes. It’s totally thread-safe. Actually, I would complain the lock is too aggressive. The whole engineNextBytes() is synchronized.

To be frank with you, I wouldn’t know if it’s not safe. The threading issue probably introduces more randomness 🙂