7 Replies Latest reply on May 14, 2009 6:35 AM by 782681

    Error in ThreadLocal's JavaDoc?

      I'm currently reading "Java Concurrency In Practice" (an excellent book,
      BTW), and was looking at the passage on ThreadLocal. I then went to the
      JavaDoc, and it sure looks to me like there's an error in the example code
      in the JavaDoc. Can someone confirm or contradict me?

      See http://java.sun.com/javase/6/docs/api/java/lang/ThreadLocal.html

      The example code looks like this:
      public class UniqueThreadIdGenerator {
      private static final AtomicInteger uniqueId = new AtomicInteger(0);
      private static final ThreadLocal < Integer > uniqueNum =
      new ThreadLocal < Integer > () {
      @Override protected Integer initialValue() {
      return uniqueId.getAndIncrement();
      public static int getCurrentThreadId() {
      return uniqueId.get();
      } // UniqueThreadIdGenerator
      It seems to me that getCurrentThreadId() should call uniqueNum.get() , not
      uniqueId.get() . uniqueId.get() would return the last unique ID generated
      in any thread, since it isn't ThreadLocal, while uniqueNum is the
      ThreadLocal ID for this thread.

      By the way, if you look at the JavaDoc for 1.4.2 and 1.5.0, it's a very similar
      example, that appears correct to me (except for the counter not being
      and AtomicInteger, since that didn't exist in 1.4.2, but the 1.5.0 example has no excuse for not avoiding that race condition).
      [1.4.2 JavaDoc for ThreadLocal.html|AtomicInteger]
      [1.5.0 JavaDoc for ThreadLocal.html|http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ThreadLocal.html]

      Am I right? Thanks.