How do you use ThreadLocal with a simple code example?

ThreadLocal is a Java class that provides thread-local variables. Each thread accessing such a variable has its own, independently initialized copy of the variable. This is particularly useful in situations where you need to store data that is confined to a single thread, such as user sessions or database connections.

Here is a simple example of how to use ThreadLocal:

import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadLocalExample { // Create a ThreadLocal variable private static ThreadLocal threadLocalValue = ThreadLocal.withInitial(() -> 1); public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(3); for (int i = 0; i < 3; i++) { final int threadNum = i; executorService.submit(() -> { // Accessing the ThreadLocal value System.out.println("Thread " + threadNum + " initial value: " + threadLocalValue.get()); // Updating the ThreadLocal value threadLocalValue.set(threadLocalValue.get() + threadNum); System.out.println("Thread " + threadNum + " updated value: " + threadLocalValue.get()); }); } executorService.shutdown(); } }

Java ThreadLocal multithreading thread-safe concurrent programming