What is ThreadLocal class, and how does it help writing multi-threading code? any usage with example?

By | March 5, 2023

The ThreadLocal class in Java provides a way to store thread-local data, which is data that is associated with a particular thread and is not shared with other threads. This can be useful in multi-threaded programs, where different threads may need to access and modify their own copies of a particular data structure, without interfering with each other.

The ThreadLocal class is typically used to store state that is specific to a particular thread, such as thread-local variables, thread-local database connections, or thread-local caches. By using ThreadLocal, you can avoid the need for synchronization or locks when accessing or modifying the thread-local state, since each thread has its own copy of the data.

Here’s an example of how to use ThreadLocal to store a thread-local counter:

public class MyThreadLocalCounter {
private static final ThreadLocal<Integer> counter = new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return 0;
}
};

public static int next() {
counter.set(counter.get() + 1);
return counter.get();
}
}

In this example, we define a ThreadLocal instance that stores an Integer value. The initialValue() method is overridden to provide a default value for the thread-local variable. We then define a next() method that increments the counter and returns its value. By using ThreadLocal, we can ensure that each thread has its own copy of the counter and that updates to the counter do not interfere with other threads.

Here’s an example of how to use the MyThreadLocalCounter class in a multi-threaded environment:

public class MyThread implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(“Thread ” + Thread.currentThread().getId() + ” counter: ” + MyThreadLocalCounter.next());
}
}
}

public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new MyThread());
Thread t2 = new Thread(new MyThread());
t1.start();
t2.start();
}
}

In this example, we create two threads, each of which runs an instance of the MyThread class. Each thread calls the next() method on the MyThreadLocalCounter class, which increments and returns the thread-local counter. The output shows that each thread has its own copy of the counter and that updates to the counter do not interfere with each other.

Leave a Reply

Your email address will not be published. Required fields are marked *