In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "why every time you run out of ThreadLocal, you have to call remove()". In daily operation, I believe many people have doubts about why every time you run out of ThreadLocal, you have to call remove(). Xiaobian consulted all kinds of information and sorted out simple and easy operation methods. I hope to answer your doubts about "why every time you run out of ThreadLocal, you have to call remove()". Next, please follow the small series to learn together!
What is a memory leak?
Memory leak refers to when an object is no longer useful, the occupied memory can not be reclaimed, this is called memory leak.
Because normally, if an object is no longer useful, then our garbage collector GC should clean up this part of memory. In this way, this part of the memory can be subsequently reallocated to other places to use; otherwise, if the object is not used, but has not been recycled, such garbage objects if accumulated more and more, it will lead to less and less available memory, and finally there is not enough memory OOM error.
Let's examine how such a memory leak occurs in ThreadLocal.
Key's leak
In the previous lecture, we analyzed the internal structure of ThreadLocal and learned that each Thread has a variable of type ThreadLocalMap, which is called threadLocals. After a thread accesses ThreadLocal, it maintains the mapping between the ThreadLocal variable and the specific instance in the Entry in its ThreadLocalMap.
We may execute the ThreadLocal instance = null operation in the business code to clean up the ThreadLocal instance, but suppose we strongly reference the ThreadLocal instance in the Entry of the ThreadLocalMap, then although the ThreadLocal instance is set to null in the business code, there is still this reference chain in the Thread class.
GC will perform reachability analysis when garbage collection, and it will find that this ThreadLocal object is still reachable, so there will be no garbage collection for this ThreadLocal object, which will cause a memory leak.
JDK developers took this into account, so Entry in ThreadLocalMap inherits WeakReference weak references, as follows:
static class Entry extends WeakReference> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal k, Object v) { super(k); value = v; } }
As you can see, the line value = v represents the occurrence of a strong reference.
Under normal circumstances, when the thread terminates, the value corresponding to the key can be collected by normal garbage collection, because no strong references exist. But sometimes the thread life cycle is very long, if the thread does not terminate, then ThreadLocal and its corresponding value may no longer be useful. In this case, we should ensure that they can be recycled properly.
To better analyze this problem, let's use the following diagram to look at specific reference links (solid lines represent strong references, dashed lines represent weak references):
As you can see, on the left is the reference stack, which has a ThreadLocal reference and a thread reference, and on the right is our heap, in the heap are instances of objects.
Let's focus on the following link: Thread Ref → Current Thread → ThreadLocalMap → Entry → Value → Possible leaked value instances.
This link exists as long as the thread exists, and if the thread performs a time-consuming task without stopping, then this Value is reachable when garbage collection performs reachability analysis, so it will not be collected. But at the same time we may have completed the business logic processing, no longer need this Value, this time also occurred memory leak problem.
JDK also considers this problem. When executing ThreadLocal's set, remove, hash and other methods, it will scan Entry with null key. If it finds that the key of an Entry is null, it means that its corresponding value has no effect, so it will set the corresponding value to null. In this way, the value object can be recovered normally.
But assuming ThreadLocal is no longer used, then the set, remove, and rehash methods will not actually be called, and at the same time, if the thread survives and does not terminate, then the call chain will always exist, which will lead to the memory leak of value.
How to avoid memory leaks
After analyzing this problem, how can we solve it? The solution is the title of this lesson: call the remove method of ThreadLocal. Calling this method deletes the corresponding value object and avoids memory leaks.
Let's look at the source code for the remove method:
public void remove() { ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) m.remove(this); }
As you can see, it first gets the reference to ThreadLocalMap and calls its remove method. The remove method here can clean up the value corresponding to the key, so that the value can be recovered by GC.
So, after using ThreadLocal, we should manually call its remove method to prevent memory leaks.
At this point, the study of "why remove() should be called every time ThreadLocal is used up" is over, hoping to solve everyone's doubts. Theory and practice can better match to help you learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!
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.