Before we start….
ThreadLocal is your answer to:-
If you want the object to be thread-safe but at the same time it does not hamper the performance of your application.
If you don’t want to create a new object each time new thread task is being assigned.
If you want to share the same object between multiple method calls without actually passing the object as parameters.
Write a better and clean code in a multithreaded environment.
If that excites you lets take a deep dive in!
Scenario 1:- Creating new objects per thread request.
Consider the above situation where you are creating a new object for each thread request. Despite the fact, this implementation might work it is very inefficient to use when a large number of requests needs to be served.
For E.g. For 1000 new threads, 1000 new objects will be created.
If we think about it for an application which serves millions of requests in a day would it be feasible?
To overcome the issue of thread creation for each new request we use Thread Pools.
Using thread pools we create a predefined number of threads which can be used and allotted tasks an innumerable number of times thereby reducing the overall thread cycle overhead.
Scenario 2:- Sharing the same object per thread request.
- The solution to the previous problem i.e. creating new object per thread request is to use the same object for every thread.
- Two cases arise in this circumstance i.e. either the object is non-synchronized or it is synchronized.
- If the object is non-synchronized the object can be shared by multiple threads at the same time. This will prompt undesired outputs since one thread does not have authority over the object.
- If we synchronize the object i.e. lock the object when one thread is accessing it we can achieve the desired results but at the cost of lowered performance since threads have to wait until the object is freed up by the other thread.
Imagine this as having a single computer being shared by multiple people. If the computer is restricted for one person use each time it is being accessed other people would have to queue up for their turn to arrive. This is synchronization.
On the other hand, if all the people can simultaneously access the computer no one would be able to get the desired output. These are non-synchronized objects.
Scenario 3:- Assigning one object per-thread using ThreadLocal.
- The developers at Oracle then came with a solution to all the above problems with the concept of ThreadLocal.
- Using ThreadLocal you can assign one Object to each ThreadPool Object.
- As you can see in the image above, one object belongs to one thread object. thereby enabling concurrency. For example for a thread pool with 100 Threads, 100 local objects would be assigned individually for each thread such that each thread can work and process requests independently of others.
Imagine this as each person being allotted his personal computer. The advantage is that each of them can use their own computers without interrupting the workflow of others or without queuing up thereby improving the overall throughput.
Advantages of ThreadLocal:-
ThreadLocal enables you to have per-thread data, enabling concurrency, without compromising your overall system design.
Reducing the code complexity since you no longer need to pass the objects as arguments. In the scenario where multiple services want to have access to the same object data, it can simply access it using the thread without using any data structure such as ConcurrentHashMap.
Improves memory efficiency/effectiveness as new objects are not created for every thread request.
Thread-safety won’t be a concern which needs to be handled separately thereby improving the efficiency of the developers and the program is less prone to glitches/bugs.
Note:- Although ThreadLocal objects might be useful while developing a multithreaded application, it is really important to use it wisely and clear the ThreadLocal objects otherwise you might end up having a java.lang.OutOfMemoryError due to memory leaks in the case where you are using Thread Pool managed by the application servers.
In this article, we discussed the situations in which it is beneficial to use ThreadLocal and its advantages. I hope you liked the article. In the coming article, I will attempt to clarify the above concepts by taking a code snippet which would help you to go through the implementation of ThreadLocal.
If you have any queries feel free to shoot them in the comment section below. Hope you have a great day ahead :)