Java OCA OCP Practice Question 3015

Question

Which one of the following options is best suited for generating random numbers in a multi-threaded application?.

  • a) Using java.lang.Math.random()
  • b) Using java.util.concurrent.ThreadLocalRandom
  • c) Using java.util.RandomAccess
  • d) Using java.lang.ThreadLocal<T>


b)

Note

java.lang.Math.random() is not efficient for concurrent programs.

Using ThreadLocalRandom results in less overhead and contention when compared to using Random objects in concurrent programs (and hence using this class type is the best option in this case).

java.util.RandomAccess is unrelated to random number generation.

this interface is the base interface for random access data structures and is implemented by classes such as Vector and ArrayList.

java.lang.ThreadLocal<T> class provides support for creating thread-local variables.




PreviousNext

Related