background
-
Understanding ThreadLocal 1: Basics and Applications
-
Read ThreadLocal for Understanding 2: Memory Leak process analysis and its solution
-
I recommend reading ThreadLocal for Understanding 3: Problems with thread pools and their solutions
-
What is the Thread and ThreadLocalMap relationship?
-
How do ThreadLocal and ThreadLocalMap relate to each other?
-
What is the relationship between ThreadLocalMap and Entry?
-
At what stage is the relationship constructed? Like ThreadLocalMap in Thread?
process
- The class diagram relationship
2. Runtime data layout
- The ThreadLocal structure designs the layout
Understand that each thread has a private ThreadLocalMap instance.
-
What does the developer’s custom ThreadLocal static attribute mean?
A) Assign threadLocals to the current thread, which helps generate an instance of ThreadLocalMap.
B) K in Entry is our developer’s custom ThreadLocal instance variable. Weak references.
summary
-
Document the class diagram relationships associated with ThreadLocal.
-
ThreadLocal runtime memory structure layout.
-
The layout of the internal structure of ThreadLocal.
-
The working process of the
A) a developer-defined ThreadLocal instance calls the set() method
Get the current thread directly, and then get the ThreadLocalMap instance of the current thread directly. If null, an instance of ThreadLocalMap is created and assigned to the current thread, and the value (T v) is placed into entry[] in the map; If the value is not null, set the value directly.
B) the developer custom ThreadLocal instance calls the get() method
Get the current thread directly, and then get the ThreadLocalMap instance of the current thread directly. If null, set the initial value. The logic for setting the initial value is to perform its default initialization setting, which is null, then get the current thread, then get the ThreadLocalMap instance of the current thread, and if null, create the ThreadLocalMap instance and assign it to the current thread. And put the value (T v) into the map entry[]; If it is not null, the value is obtained directly.
-
Understand the class diagram relationships of ThreadLocal, as well as the internal structure design layout of ThreadLocal and the memory layout of ThreadLocal data at runtime. And our work process is just to build the relationship between these foundations, that is, we design the basic components, using the work process (working principle) or what we call the algorithm, to organize and coordinate these basic components, so that they orderly complete their corresponding functions.