How ThreadLocal works in Java

Java ThreadLocal is used to create thread-local variables. In multithreaded environment all threads of an Object share its variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables.
Every thread has its own ThreadLocal variable and they can use its get() and set() methods to get the default value or change its value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.
Here is a small example showing use of ThreadLocal and proving that every thread has its own copy of ThreadLocal variable.

 

Thanks for your reading. Please leave a comment.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.