Overview of ThreadLocal in Java

Muhammad Adil Feb 15, 2023
  1. Main Use of ThreadLocal Variable
  2. to Use a ThreadLocal in Java
Overview of ThreadLocal in Java

ThreadLocal is a powerful tool in the Java language that allows developers to create variables specific to each thread of execution. This means that each thread has its copy of the variable, independent of the values of the same variable in other threads.

This is particularly useful in multi-threaded applications, where different threads may have different requirements for a given variable and where changes to the value of a variable in one thread shouldn’t affect the value of the same variable in another thread.

Main Use of ThreadLocal Variable

The main use case for ThreadLocal is to store a per-thread state, such as a user ID or transaction ID, that is specific to a single request and should not be shared between different requests.

For example, consider a web application that uses a single database connection to handle multiple user requests. Without ThreadLocal, it would be difficult to ensure that each request uses the correct user information, as multiple requests could be executed simultaneously by different threads and interfere with each other.

With ThreadLocal, each thread can store its user information, which will be used by the database connection associated with that thread.

to Use a ThreadLocal in Java

To use ThreadLocal in Java, you declare a new instance of the ThreadLocal class and then use its get() and set() methods to access and modify the value associated with the current thread.

For example, the following code demonstrates using a ThreadLocal to store a user ID for each thread.

public class Main {
    public static void main(String args[]) {
      ThreadLocal<Integer> localVariable = new ThreadLocal<>();
// get the value for the current thread
System.out.println("Value of localVariable in current thread: " + localVariable.get());

When you create a ThreadLocal variable, each thread that accesses it has its separate instance of the variable. This means that each thread can store a different value for the same ThreadLocal variable, and when it accesses the variable, it will get the value set for that specific thread.

This can be useful in multi-threaded environments, where you must store thread-specific data that should not be shared between threads.

For example, you can use a ThreadLocal variable to store information such as the user ID or transaction ID for a specific thread to track the data for that thread, even if multiple threads are executing simultaneously.

It is important to note that ThreadLocal does not automatically remove its value when the thread that created it terminates. This can lead to memory leaks, as the values associated with the terminated threads will continue to occupy memory.

It is recommended to use the remove() method of the ThreadLocal class or to use the try-with-resources statement in Java 7 and later to avoid this. For example:

try (ThreadLocalCleanup cleanup = new ThreadLocalCleanup(userId)) {
    // use the ThreadLocal variable here

In this example, the ThreadLocalCleanup class implements the AutoCloseable interface, which allows it to be used with the try-with-resources statement.

When the try-with-resources statement is exited, the close() method of the ThreadLocalCleanup class is automatically called, which removes the value associated with the current thread from the ThreadLocal variable.

Click here to check the working of the code mentioned above.

Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.


Related Article - Java Thread