• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Newbie to ThreadLocal

 
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Author
Posts: 986
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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 ]
 
John McDonald
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 986
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.)
 
Bartender
Posts: 1638
IntelliJ IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A word of caution: Beware while using ThreadLocals when your code is being executed in an environment where threads are reused(eg: threadpools).
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic