[concurrency-interest] TLR Puzzle

Peter Levart peter.levart at gmail.com
Thu Feb 20 05:28:02 EST 2014

On 02/19/2014 08:51 PM, Zhong Yu wrote:
>      static ThreadLocalRandom random;
>      public static void main(String[] args) throws Exception
>      {
>          Thread t1 = new Thread( () ->
>              random=ThreadLocalRandom.current()
>          );
>          t1.start();
>          t1.join();
>          System.out.println( random.nextInt() ); // is the result random?
>      }

A 3rd possibility: If by thread-local variable we mean an object 
referenced by ThreadLocal(s), then Zhong Yu is right, such object(s) can 
often be safely accessed (used) by multiple threads if their access/use 
is synchronized. Not so with ThreadLocalRandom instance(s). So perhaps 
this should be spelled out in the javadoc. What about:

<p>Usages of this class should typically be of the form: {@code
ThreadLocalRandom.current().nextX(...)} (where {@code X} is {@code
Int}, {@code Long}, etc).  When all usages are of this form, it is
never possible to accidentally *use a {@code ThreadLocalRandom} **instance
**in a thread that did not obtain it via a call to {@code 
A {@code ThreadLocalRandom} instance should never be made
accessible to other threads by, for example, holding in a {@code
static} field*, even when access to and use of ***{@code 
ThreadLocalRandom} instance **
* is synchronized.* A {@code ThreadLocalRandom} used by multiple threads
need not (and typically will not) generate uniform random numbers.

Regards, Peter

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20140220/77386fbe/attachment.html>

More information about the Concurrency-interest mailing list