Sub Topic in Threads — ThreadLocal

Sub Topic in Threads — ThreadLocal

If you are reading this article, you must be having basic understanding of the threads concept. If not, do not worry, you can read my previous article.

Multi Threading — Basics Explained in simple way

Now that we know threads and how to create them, we can explore on some of the terminologies used in Threads concept. One of them is ThreadLocal.

What is the use of ThreadLocal?

As I learnt Threads concept, I started using it. I got this situation where I am creating the web application and used this thread concept to retrieve data of customer from database.

I have multiple customers and I have to retrieve only the customer specific data. For this I need a variable or an object which can hold customer specific data and we also know that each customer data is retrieved in each thread.

Now I have a thought, what is I can create an object which is thread specific. Here comes the concept of ThreadLocal

The way to create a ThreadLocal Object is

ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>();

Here I mentioned Integer as I need an Integer value. You can specify the data type based on your needs.

Now that object is created, I want to store the value specific to my thread

threadLocalValue.set(5);

set method sets the value of threadlocal value to 5 which internally stores the value in the form of Map where key is the Thread and value is 5.

The way we retrieve the value is as follows

Integer result = threadLocalValue.get();

We can also initiate the value of ThreadLocal using the static method. Here the instance of threadlocal is created with an initial value of 1

ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 1);

We can also remove the value

threadLocal.remove();

Now that we know all about ThreadLocal, let us think of scenarios where it causes the problem.

I have a ThreadPool where each Thread is assigned to a customer to get their data and is assigned to ThreadLocal. Perfect!!

What if my thread finish working on the customer data and returned to the threadpool and picks up other customer data and the previous data is still remaining if we do not erase the data properly.

This will lead to a problem.

The solution for this to make sure that we erase the data entered in ThreadLocal by the thread is using the method afterExecute()

public class ThreadLocalAwareThreadPool extends ThreadPoolExecutor {         
@Override
protected void afterExecute(Runnable r, Throwable t) {
// Call remove on each ThreadLocal
}
}

To use the method we have to extend the class ThreadPoolExecutor which will be executed when the thread is returned to the threadpool

Great!!! Hope you are all clear with this concept.