Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I prefer ThreadLocalRandom or SecureRandom?

I know that Random class generates insecure random sequences and I should prefer using SecureRandom when dealing with security. But what about ThreadLocalRandom? Is it more or less secure?

// generate a five-digit numeric confirmation code
Long code = ThreadLocalRandom.current().nextLong(1, 99999);
like image 988
naXa Avatar asked Jun 12 '17 14:06

naXa


People also ask

When to use ThreadLocalRandom in Java?

Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask ) use random numbers in parallel in thread pools. Usages of this class should typically be of the form: ThreadLocalRandom. current().

How does ThreadLocalRandom work?

A ThreadLocalRandom is initialized using an internally generated seed value that is not otherwise modifiable. Using ThreadLocalRandom instead of shared instances of Random will result in low contention and overhead. ThreadLocalRandom, just like its parent class, is not cryptographically secure.


1 Answers

As described in its javadoc, ThreadLocalRandom is similar to Random (i.e. not secure) but with better performance in case of concurrent access.

Instances of ThreadLocalRandom are not cryptographically secure. Consider instead using SecureRandom in security-sensitive applications.

like image 89
assylias Avatar answered Sep 19 '22 02:09

assylias