• Post Reply Bookmark Topic Watch Topic
  • New Topic

where i need to use the ThreadLocal in Real world?  RSS feed

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi..

i have Question that Where we need to use the ThreadLocal In Real world Example..???

Thanks,
Ramakrishna Rayudu.
 
Ranch Hand
Posts: 116
Eclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
ramakrishna rayudu
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!