In other words, ThreadLocal is used to provide thread-safety without contention, which comes due to locking, either by using synchronized keyword or Java 1.5 Lock framework. Since every thread has there own copy, no data is shared between threads, which means no need of synchronization and no multithreading issues.
By the way careless use of ThreadLocal variable in a managed environment like web servers can cause classloader memory leak in Java. Since managed environment use thread pool, which is shared between web applications, there actual life span is more than web application. Since every thread keep a reference of threadlocal variable, it could prevent it from Garbage collected and subsequently to the classloader, which is loaded it.
In order to avoid this issue, remember to remove Threadlocal variable, once you are done with that. Filter is right place to create and remove Threadlocal variable in Java web application.
ThreadLocal is also a parameterized class in Java, which means you can store only Objects there. And if you are wondering when to use ThreadLocal variables, let me tell you that one of the common use of ThreadLocal variable is to make SimpleDateFormat thread-safe.
Important things about ThreadLocal variables in Java
1) ThreadLocal variables are JDK supplied per-thread variable. It Enables reuse of expensive object without introducing expensive synchronization and concurrency problems. A Java application can create any number of thread local variable.
2) Objects which are heavily used, but expensive to create are good candidate for storing as ThreadLocal variable. Converter, formatter e.g. SimpleDateFormat, factory e.g. BorderFactory, Connection e.g. SQLConnection, are some practical objects which can be reused safety by using ThreadLocal concept.
3) Storing inexpensive objects in ThreadLocal is not recommended, objects like Integer, Double or String are not that expensive and can be created on local context. Also remember that access to a ThreadLocal variable is usually a hash lookup, so if performance is critical and creating object take less time than retrieving existing one, prefer local variable.
That’s all about what is ThreadLocal variable in Java and when to use them. They are a good feature of Java but tricky one to use. There are not many use cases where you really want to use ThreadLocal but if you know concurrency well and you have a object which is not shared between threads you can use store that into ThreadLocal variable. For example, you can create an app where order from a particular city is process by one thread and order from a different city is process by other thread.
Related Java multithreading Tutorials from Javarevisited Blog
Thanks for reading this article of far. If you find this Java thread tutorial useful then please share it with your friends and colleagues. If you have any
questions or feedback then please drop a note.