In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what is the structure of ThreadLocal". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what is the structure of ThreadLocal"?
Content outline
Java object reference level
Before talking about ThreadLocal, let's lay the groundwork for knowledge and talk about the reference level of Java objects.
In order to make the program more flexible to control the life cycle of objects, starting from the JDK1.2 version, JDK divides the reference level of objects from high to low into four levels: strong reference, soft reference, weak reference and virtual reference.
Strong reference to StrongReference
Strong reference is our most common object, it belongs to non-recyclable resources, garbage collector (hereinafter referred to as GC) will never reclaim it, even if there is insufficient memory, J V M would rather throw an OutOfMemoryErrorM exception to terminate the program than to collect strong reference objects.
Soft reference SoftReference
If the object is a soft reference, then its nature is optional, because when there is sufficient memory space, G C will not reclaim it, but memory space is tight, G C finds that it only has a soft reference, it will recycle the object, so the soft reference object is suitable to be used as a memory sensitive cache object.
Only objects referenced by WeakReference are weak reference-level objects, because objects can be referenced in multiple places, so objects referenced by WeakReference may be strongly referenced elsewhere.
Virtual reference PhantomReference
As the name implies, virtual references are nonexistent, and unlike several other references, virtual references do not determine the life cycle of an object.
If an object has only virtual references, it can be recycled by GC at any time, just as it does not have any references.
ThreadLocal
ThreadLocal is called thread local variable in many places and thread local storage in some places, but it actually means much the same thing. ThreadLocal creates a copy of the variable in each thread, and each thread can access its own internal copy variable.
What is ThreadLocal?
The Thread class declares that the member variable threadLocals,threadLocals is the real thread-local variable, so each Thread has its own thread-local variable, so the thread-local variable has thread isolation, which is inherently thread-safe.
From the figure above, we can see that the threadLocals member variable class is ThreadLocal.ThreadLocalMap, that is, the internal class provided by ThreadLocal, so the core of the creation, addition, acquisition and deletion of Thread thread local variables must be around threadLocals, so the developers also implement the function around threadLocals, and for subsequent reuse, the code implementation will be encapsulated and reused, while ThreadLocal is the thread local variable tool class, provided by J D K. The functions of thread local variables have been implemented and can be used out of the box for the benefit of developers.
Common methods of ThreadLocal
Set: sets the variable for the current thread, with the current ThreadLocal as the index
Get: gets the current thread variable, with the current ThreadLocal as the index
InitialValue (hook method requires subclass implementation): initialize thread local variables in loading form. When executing get, if you find that the thread local variables are null, the contents of initialValue will be executed.
Remove: clears the ThreadLocal index and mapped elements of the current thread
Now it is concluded that "the scope of local thread variables belongs to the entire scope of the current thread, and a thread can use local thread variables across multiple methods." when you want some variables to be shared in multiple methods of a Thread and ensure thread safety, then boldly use ThreadLocal (ps: be sure to figure out whether a variable is shared by multiple methods in the Thread life cycle, or whether multiple Thread share this variable! ).
ThreadLocal source code
Let's take a look at the thread-local variable code implemented by the User class
Through the above picture, I believe that everyone has a very clear structure of ThreadLocalMap, I do not know if there is a careful partner found that ThreadLocal is held by weak quotes?
Why is ThreadLocal weakly referenced? This piece of doubt will be clearly arranged for everyone, and the last ThreadLocalMap source code map.
The steps are as follows
Get the current thread
Gets the local variable of the current thread
Thread local variable is not created, execute setInitialValue method to initialize, and return value value
Thread local variable exists, and ThreadLocal is calculated as an index to get Entry from local thread variable. If Entry is null, execute setInitialValue method to initialize it and return value value, otherwise value is returned by Entry.
InitialValue method
The steps are as follows
Get the current thread
Get thread local variables
The local variable is not empty. The current ThreadLocal sets the mapped value for the index. Otherwise, create the thread local variable and then do the subsequent setting operation.
Remove clears variables
Why weak references are used
Why do I use weak references to ThreadLocal in Entry? On the contrary, what happens if you use strong quotes?
We don't know what key is and how to get the mapped value. By the same token, there is no entrance to get the ThreadContextTest.ThreadLoca, so there is no way to get the mapped Entry element.
In the design, the Map structure is used to store data, but the value can not be obtained through key, which is obviously unreasonable, and because the key and value values are strong references, G C can not be recycled, resulting in memory overflow.
So J D K is optimized for this unreasonable design scenario, using weak references to the ThreadLocal in Entry. When G C finds that it has only weak references, it will be recycled.
The meaning behind remove
It's not over yet. There's a small tail left on it. Everyone knows that weak references are used for ThreadLocal in Entry, but value is a strong reference. If the unreasonable scenario mentioned above occurs, the value value cannot be cleaned up, resulting in memory overflow.
In fact, value as a strong reference design is reasonable, if you use soft or weak reference, there will be a big problem, the program is running suddenly get to a null, it is estimated to have to scold the mother, so to solve the memory overflow problem J D K provides remove method, so that developers can choose to manually clean up the entire Entry element to prevent memory overflow.
Do you remember what you said before? Thread local variable life cycle and thread binding, the general thread life cycle is relatively short, when the thread ends, thread local variables will be destroyed naturally, soft references and remove will not be a little redundant?
Business is rapidly changing, and in most cases, the life cycle of threads is relatively short, but business scenarios will also lead to longer life cycle of threads, or even infinite loop execution of threads. You can't expect this. Once the quantity comes up, it is easy to overflow memory, so it is recommended to clean up the ThreadLocal in time after use, for the following reasons
Thread scenarios with long life cycle
The scenario of an infinite loop thread
Thread pool scenario (because thread pools can be reused, and the framework used by the company may customize thread pools, you can't guarantee that they will help you remove in the thread pool)
At this point, I believe you have a deeper understanding of "what is the structure of ThreadLocal". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.