[concurrency-interest] ThreadLocal example bug.
Pete.Soper at Sun.COM
Pete.Soper at Sun.COM
Wed Sep 27 13:20:20 EDT 2006
Hi Jason,
For the example code field uniqueId is a "dispenser" of the
next available id value and that is used once per thread (but is visible
to all threads) via the overriden initialVlaue method invocation that is
a side effect of the first invocation of uniqueNum.get. The per-thread
value is maintained by ThreadLocal code that you can't see and it never
changes for a given thread. But maybe I'm missing something. Do you have
a misbehaving test?
Regards,
Pete
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
More information about the Concurrency-interest
mailing list