[concurrency-interest] ThreadLocal example bug.
Pete.Soper at Sun.COM
Pete.Soper at Sun.COM
Wed Sep 27 14:14:43 EDT 2006
Oh. I thought the fragment of the class file Tom sent me was the code in
question. Dang.
Pete
Jason Mehrens wrote:
> Pete,
>
> The code you have attached bellow is correct (and what i would expect
> to see) however, it is not the code out on the web. From
> http://download.java.net/jdk6/docs/api/java/lang/ThreadLocal.html
>
> import java.util.concurrent.atomic.AtomicInteger;
>
> 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
>
>
> Regards,
>
> Jason Mehrens
>
>
>> From: Pete.Soper at Sun.COM
>> To: Jason Mehrens <jason_mehrens at hotmail.com>
>> CC: concurrency-interest at cs.oswego.edu
>> Subject: Re: [concurrency-interest] ThreadLocal example bug.
>> Date: Wed, 27 Sep 2006 13:20:20 -0400
>>
>> 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