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 ]