How ThreadLocal variables works in Java? Explained

Hello guys, ThreadLocal variable is an interesting concept and class from Java API. Not many developer knows about it and very few know how to use it correctly. A couple of years ago it was also a popular Java interview questions for experienced developer but over the years, it lost the popularity as more and more people are now asking about Phaser, CompletableFuture, ForkJoinPool, and other newly added concurrency utilities. ThreadLocal variables, as name suggests is local to thread, which means every thread has there own copy. This means they don't need to look at the main memory when they want to use that variable and best thing is that the variable is not even shared between threads so no locking or synchronization is needed. 
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. 

This can cause a classloader memory leak, which happens if you deploy and undeploy your web application couple of times, which eventually lead to java.lang.OutOfMemoryError: PermGen Space in Tomcat or any other web server. 

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. 

By the way, this scenario will not occur if you only store objects loaded by BootStrap classloader into ThreadLocal, this isssue comes, when you store application classes as ThreadLocal, which was loaded be web app classloaders.

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

Here are important thing every Java developer should know and remember before using ThreadLocal variable in their application

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.

Here is an example of How ThreadLocal variable works in Java:

What is ThreadLocal Variable in Java?

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

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.