[concurrency-interest] TLR Puzzle

Dr Heinz M. Kabutz heinz at javaspecialists.eu
Tue Feb 18 10:36:32 EST 2014


A little newsletter on this subject to warn my readers to never let 
their ThreadLocalRandom instances escape. 

http://www.javaspecialists.eu/archive/Issue218.html

For the young-at-heart amongst you (or generally curious), there is 
another puzzle (along the same theme as before):

What happens when you run this on Java 7?  On Java 8?

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.*;

import static javax.swing.WindowConstants.*;

public class MagicMessage {
  public static void main(final String... args) {
    final ThreadLocalRandom tlr = ThreadLocalRandom.current();
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        final JFrame frame = new JFrame();
        final JLabel label = new JLabel(
            generateRandomString(), SwingConstants.CENTER);
        frame.add(label, BorderLayout.NORTH);
        frame.setSize(300, 100);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
      }
      private String generateRandomString() {
        final char[] randomText = "HVTia\u000EDlciP".toCharArray();
        for (int i = 0; i < randomText.length; i++) {
          randomText[i] += tlr.nextInt(26);
        }
        return new String(randomText);
      }
    });
  }
}

Regards

Heinz
-- 
Dr Heinz M. Kabutz (PhD CompSci)
Author of "The Java(tm) Specialists' Newsletter"
Oracle Java Champion 2005-2013
JavaOne Rock Star Speaker 2012
http://www.javaspecialists.eu
Tel: +30 69 75 595 262
Skype: kabutz



Doug Lea wrote:
>
> To summarize, we have the following suggestions (some off-list)
> in response to Heinz's puzzler:
>
> 1. Add documentation to TLR warning not to store TLR.current()
> in a static, or use as an argument to a method that might do so,
> or use as an argument in a method assuming thread-safety.
>
> 2. Add similar documentation to java.lang.ThreadLocal, and then
> refer and add to it in TLR.
>
> 3. Create findBugs rules covering (1) and (2).
>
> 4. Invent new type rules for Java enforcing (1) and (2).
>
> 5. Add an initialization check on each use of TLR.next() and
> throw an exception.
>
> 6. Eagerly initialize TLR seeds. (One reason this was not
> done originally is that it adds measurable time to Thread
> construction even when TLRs are not used in a thread, which
> is the most common case.)
>
> 7. Tell people to use java.util.SplittableRandom instead.
>
> 8. Do nothing.
>
> Considering that this is far from a critical bug, it is
> unlikely to become updated in OpenJDK until JDK9, so we
> seem to have plenty of time for further suggestions!
>
> -Doug
>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
> .
>


More information about the Concurrency-interest mailing list