Multithreading With ThreadLocal, Making Threads Work for You.

Prateek Nima
Nov 3, 2020 · 4 min read

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.

Illustration 1: A new object is created for each 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.
Non-Synchronized Shared Objects
  • 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.
Synchronized Shared Objects
  • 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 :)

The Startup

Get smarter at building your thing. Join The Startup’s +787K followers.

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Prateek Nima

Written by

Curious and Codelicious!

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Prateek Nima

Written by

Curious and Codelicious!

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store