| Author |
where i need to use the ThreadLocal in Real world?
|
ramakrishna rayudu
Ranch Hand
Joined: Mar 08, 2011
Posts: 57
|
|
Hi..
i have Question that Where we need to use the ThreadLocal In Real world Example..???
Thanks,
Ramakrishna Rayudu.
|
 |
Chris Beckey
Ranch Hand
Joined: Jun 09, 2006
Posts: 116
|
|
|
The most common usage I know of is to attach security context (user identification, credentials, groups, etc...) to a thread servicing an HTTP request. In that way any of the "downstream" called methods can check the permissions of the original caller.
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12921
|
|
With a ThreadLocal, you can create one copy of some value per thread - so if you have multiple threads that access the value, there will be a separate copy for each thread.
One of the examples that this is sometimes used with is with SimpleDateFormat. Class SimpleDateFormat is not thread-safe; you must not try to use the same SimpleDateFormat object from different threads at the same time, because then you'll get strange results and maybe even exceptions. Look at this:
To avoid such problems, you can wrap the SimpleDateFormat in a ThreadLocal, so that there will be a separate instance for each thread:
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
ramakrishna rayudu
Ranch Hand
Joined: Mar 08, 2011
Posts: 57
|
|
Thanks for Your Replay..
i didnt get the correct usage.what i got it from your answer is when ever i kept a Object In to the ThreadLocal it will return the
single Instance per Threadn is correct or not..???
Thanks,
Ramakrishna Rayudu
|
 |
 |
|
|
subject: where i need to use the ThreadLocal in Real world?
|
|
|