It's not a secret anymore!*
The moose likes Threads and Synchronization and the fly likes Newbie to ThreadLocal Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Newbie to ThreadLocal" Watch "Newbie to ThreadLocal" New topic
Author

Newbie to ThreadLocal

John McDonald
Ranch Hand

Joined: Jul 01, 2003
Posts: 112
Hi Gurus,
I start learning ThreadLocal. I have basic knowledge that is a separate thread to hold a separate value but I don't know if there its practical usage. Could you explain it? Is ThreadLocal useful?

I have the following code

The output is:
New local thread + Thread-0
New local thread + Thread-1
Thread Thread-1 has client Client[2]
Thread Thread-0 has client Client[1]


But if I change the initialValue method to be:

Then output is:
New local thread + Thread-0
New local thread + Thread-1
Thread Thread-1 has client Client[1]
Thread Thread-0 has client Client[1]


Could someone show me why? Much appreciated.

[ Edited to use code tags - Paul Sturrock ]
[ April 14, 2008: Message edited by: Paul Sturrock ]
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
Originally posted by John McDonald:
I start learning ThreadLocal. I have basic knowledge that is a separate thread to hold a separate value but I don't know if there its practical usage. Could you explain it? Is ThreadLocal useful?


It can be useful, but I have seen it mostly used for synchronization (as in this example).


But if I change the initialValue method to be:

protected synchronized Object initialValue()
{
System.out.println("New local thread + " + getName());// + " client Number " + id);
return new Client(++clientNum ;
}

Then output is:
New local thread + Thread-0
New local thread + Thread-1
Thread Thread-1 has client Client[1]
Thread Thread-0 has client Client[1]


Could someone show me why?


Well if the smiley icon represents a semicolon and a close paren, then it's a syntax error, so it got munged somehow. (Disregarding the semicolon inside the paren, it should work exactly the same. I couldn't explain why Client[1] would be printed twice.)

[begin edit]
Looking closer at your code, I see you are doing this:
Thread t1 = new ThreadLocalDemo();
Thread t2 = new ThreadLocalDemo();

This means you are instantiating two instances of ThreadLocal. Each has its own synchronized initialValue() method, but they are not synchronized with each other. This means t1.myClient.initialValue() and t2.myClient.initialValue() have a pedestrian race condition where it's possible for both to return 1. It has nothing to do with how you rewrote the initialValue() method.

Here's an attempt to "fix" your ThreadLocalDemo code with minimal changes.Even though this has been "fixed," I wouldn't say it's an especially good demonstration of ThreadLocal usefulness.
[end edit]
[ April 14, 2008: Message edited by: Brian Cole ]

bitguru blog
John McDonald
Ranch Hand

Joined: Jul 01, 2003
Posts: 112
Thank you very much for a quick reply. Can you point out the different outcome when I just changed the way I input initial value to Client object? Thanks much.

John
Brian Cole
Author
Ranch Hand

Joined: Sep 20, 2005
Posts: 862
Originally posted by John McDonald:
Thank you very much for a quick reply. Can you point out the different outcome when I just changed the way I input initial value to Client object?


I actually modified my original post after taking a second look at your code and noticing that you were essentially misusing ThreadLocal.

Please take a look between the [begin edit] and [end edit] markers I put in for an explanation, though it turns out it had nothing to do with the change you mention. I probably should have posted a new entry instead of modifying the earlier one, and for that I apologize.

Btw, you might do better asking about ThreadLocal in the Threads and Synchronization forum rather than in this one.
[ April 14, 2008: Message edited by: Brian Cole ]
John McDonald
Ranch Hand

Joined: Jul 01, 2003
Posts: 112
Thanks and apologize for being a wrong forum. So I still puzzle of ThreadLocal. I googled a lot but don't find a good sample and well explanation. I have a java concurrency in practice but I don't see it much. Do you have any good source? And also does ThreadLocal have another alternative? Thanks again.

John
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Generally, a ThreadLocal can be useful if you need some object which is (a) expensive to create, and (b) should only be used by one thread at a time. They are not used for communication between threads; rather they are used to isolate the effects of one thread from another.

Java Concurrency in Practice has a discussion of ThreadLocal in section 3.3.3. They show a good example where ThreadLocal can be useful: each thread needs a Connection, and you never want two threads to share a Connection. But you don't want to create a new Connection object every time a Connection is needed. So the ThreadLocal is a way to keep a set of Connection objects, one per thread. Anytime you need a Connection, you get the one associated with your current thread, which no other thread is using.

[John]: And also does ThreadLocal have another alternative?

Using the Connection example: one alternative would be for each thread to create a new Connection object, stored in a local variable. This would ensure that no other thread is using the same connection. But a Connection is expensive to create, so this will be slower.

Another alternative is to create a pool of connections and put them in a shared pool. This will require some sort of synchronization to access the pool. It will also require clients to do something to return objects to the pool, letting the pool known that it's now OK for another thread to use the connection. The synchronization may be a little slower than using ThreadLocal, and the code may be more complex and easier to get wrong. (Though of course there are existing tools & frameworks that can do this for you.)


"I'm not back." - Bill Harding, Twister
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

A word of caution: Beware while using ThreadLocals when your code is being executed in an environment where threads are reused(eg: threadpools).


apigee, a better way to API!
 
Don't get me started about those stupid light bulbs.
 
subject: Newbie to ThreadLocal