Java Reference
In-Depth Information
icLong instance'sinternallongintegervariableby1andreturnsthepreviousvaluein
one indivisible step.
Additional Concurrency Utilities
As well as supporting the Java 5-introduced concurrency utilities, Java 7 introduces
a pair of concurrency utilities that improve performance, which is achieved in part
by taking full advantage of multiple processors/cores. These utilities consist of the
java.util.concurrent.ThreadLocalRandom class and the Fork/Join
The ThreadLocalRandom class describes a random number generator that is isol-
ated to the current thread. In other words, it can be accessed from the current thread
Aswiththeglobalrandomnumbergeneratorusedbythe java.lang.Math class
(and which I discuss later in this chapter), a ThreadLocalRandom instance is ini-
tialized with an internally generated seed (starting value) that may not otherwise be
modified. When applicable, use of ThreadLocalRandom rather than calls to
Math.random() inconcurrentprogramswilltypicallyresultinmuchlessoverhead
and contention.
To use this class, first invoke ThreadLocalRandom 's static
ThreadLocalRandom current() method to return the current thread's
ThreadLocalRandom instance.Continuebyinvokingoneof ThreadLocalRan-
dom 's“ next ”methods,suchas double nextDouble(double n) ,whichreturns
a pseudorandom, uniformly distributed double value between 0 (inclusive) and the
specifiedvalue n (exclusive).Theargumentpassedto n istheupperboundontheran-
domnumbertobereturnedandmustbepositive;otherwise, IllegalArgumentEx-
ception is thrown.
The following example provides a demonstration via another “ next ” method:
int r = ThreadLocalRandom.current().nextInt(20, 40);
This example invokes ThreadLocalRandom 's int nextInt(int least,
int bound) methodtoreturnapseudorandom,uniformlydistributedvaluebetween
thegiven least value(inclusive)and bound (exclusive).Inthisexample, least is
20 ,whichisthesmallestvaluethatcanbereturned,andboundis 40 ,whichisonein-
teger greater than the highest value (39) that can be returned.
Search WWH ::

Custom Search