[concurrency-interest] ThreadLocal example bug.

Thomas Hawtin tackline at tackline.plus.com
Mon Sep 25 15:56:07 EDT 2006

Jason Mehrens wrote:
> Correct me if I am wrong but, it appears that the new ThreadLocal example in 
> b99 code has a bug in the getCurrentThreadId method.  It returns the value 
> of the counter (uniqueId) and not the value from thread local (uniqueNum).  
> June archives of the c-i list has the old traffic on this issue.


I guess that blindness that comes from viewing the same thing too often.

Perhaps following the rule of thumb that variables should be declared 
with as tight a scope as possible should be applied here:

  import java.util.concurrent.atomic.AtomicInteger;

  public class UniqueThreadIdGenerator {

      private static final ThreadLocal < Integer > uniqueNum =
          new ThreadLocal < Integer > () {
              final AtomicInteger uniqueId = new AtomicInteger(0);
              @Override protected Integer initialValue() {
                  return uniqueId.getAndIncrement();

      public static int getCurrentThreadId() {
          return uniqueNum.get();
  } // UniqueThreadIdGenerator

Tom Hawtin

More information about the Concurrency-interest mailing list