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();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?