nerdexam
Oracle

1Z0-804 · Question #128

Which statement creates a low overhead, low-contention random number generator that is isolated to thread togenerate a random number between 1 and 100?

The correct answer is A. int i = ThreadLocalRandom.current().nextInt(1, 101). public class ThreadLocalRandom extends Random A random number generator isolated to the current thread. Like the global Random generator used by the Mathclass, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise bemodified. When…

Concurrency

Question

Which statement creates a low overhead, low-contention random number generator that is isolated to thread togenerate a random number between 1 and 100?

Options

  • Aint i = ThreadLocalRandom.current().nextInt(1, 101);
  • Bint i = ThreadSafeRandom.current().nextInt(1, 101);
  • Cint i = (int) Math.random()*100+1;
  • Dint i = (int) Math.random(1, 101);
  • Eint i = new random().nextInt(100)+1;

How the community answered

(30 responses)
  • A
    77% (23)
  • B
    13% (4)
  • C
    3% (1)
  • D
    7% (2)

Explanation

public class ThreadLocalRandom extends Random A random number generator isolated to the current thread. Like the global Random generator used by the Mathclass, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise bemodified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrentprograms will typically encounter much less overhead and contention. Use of ThreadLocalRandom isparticularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers inparallel in thread pools. Usages of this class should typically be of the form: ThreadLocalRandom.current().nextX(...) (where X is Int, Long, etc). When all usages are of this form, it is never possible to accidently share a ThreadLocalRandom across multiple threads. This class also provides additional commonly used bounded random generation methods.

Topics

#ThreadLocalRandom#concurrency#random number#thread-local

Community Discussion

No community discussion yet for this question.

Full 1Z0-804 Practice