In Java, Thread-Local Storage (TLS) allows each thread to have its own independent instance of a variable. This is useful in multithreaded applications, especially when handling configurations like TLS (Transport Layer Security) settings.
When a thread accesses a TLS variable, it retrieves its own instance of that variable, meaning changes made to the variable in one thread do not affect the same variable in other threads. This can lead to cleaner code, as the state is isolated to the thread, enabling safer parallel execution.
This example demonstrates how to use ThreadLocal
to manage TLS configuration in a multithreaded application:
// Example of ThreadLocal usage in Java
public class TLSExample {
private static ThreadLocal threadLocalConfig = ThreadLocal.withInitial(() -> "Default Configuration");
public static void main(String[] args) {
Runnable task1 = () -> {
threadLocalConfig.set("Configuration from Thread 1");
System.out.println("Task 1: " + threadLocalConfig.get());
};
Runnable task2 = () -> {
threadLocalConfig.set("Configuration from Thread 2");
System.out.println("Task 2: " + threadLocalConfig.get());
};
Thread thread1 = new Thread(task1);
Thread thread2 = new Thread(task2);
thread1.start();
thread2.start();
}
}
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?