Unlocking ThreadLocal: How Java Gives Each Thread Its Own Variable
This article explains the purpose of Java's ThreadLocal class, shows a practical example with code and output images, compares it to synchronized locking, and demonstrates how ThreadLocal provides each thread with an independent variable copy for safe concurrent access.
ThreadLocal Introduction
After learning that shared data can be stored in public static variables, we realize that all threads would use the same instance. To give each thread its own independent variable, Java provides the ThreadLocal class.
ThreadLocal binds a value to each thread, acting like a global box that stores a private variable for every thread.
Example
Sample code:
Running result:
Although multiple threads access the same variable, because the variable is declared with ThreadLocal, each thread sees the value it set via its own threadLocal instance, illustrating ThreadLocal's effect.
When using ThreadLocal, each thread receives an independent copy of the variable, so changes in one thread do not affect the copies used by other threads.
ThreadLocal vs synchronized
Synchronized locking ensures that only one thread can access a variable at a time by acquiring an object lock, requiring careful analysis of when to read, write, lock, and release, which makes program design more complex.
ThreadLocal, in contrast, provides thread‑local variables without any locking mechanism, using a space‑for‑time trade‑off to give each thread its own copy and guarantee thread safety without synchronization.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
