Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is SecureRandom thread safe?

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?

like image 737
Yishai Avatar asked Sep 22 '09 17:09

Yishai


People also ask

Is SecureRandom secure?

Yes, it is secure, as long as nextInt() is secure (for the number of integers retrieved from the stream). According to the documentation of the Random#ints() method: A pseudorandom int value is generated as if it's the result of calling the method nextInt() .

Is SecureRandom ThreadSafe?

SecureRandom objects are safe for use by multiple concurrent threads. Implementation Requirements: A SecureRandom service provider can advertise that it is thread-safe by setting the service provider attribute "ThreadSafe" to "true" when registering the provider.

Which variables are thread-safe?

On its stack(basically thread stack), local primitives and local reference variables are stored. Hence one thread does not share its local variables with any other thread as these local variables and references are inside the thread's private stack. Hence local variables are always thread-safe.

Are private variables thread-safe?

Ans. Yes for sure, you are creating 101 logical threads (1 main thread + 100 other by calling start() method of thread).


1 Answers

Yes, it is. It extends Random, which 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.

like image 194
erickson Avatar answered Sep 23 '22 15:09

erickson