Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze stack closure and ThreadLocal in java thread closure

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to analyze stack closure and ThreadLocal in java thread closure. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

Thread closure

In a multithreaded environment, we often use locks to ensure thread safety, but if locks are used for resources that each thread uses, then the efficiency of program execution will be affected. At this time, these resources can be turned into thread-closed forms.

1. Stack closure

The so-called stack closure is actually the use of local variables to store resources, we know that local variables are stored in the virtual machine stack in memory, and the stack is private and independent of each thread, so this can ensure thread safety.

2 、 ThreadLocal

Let's first look at the diagram of ThreadLocal and thread Thread.

Take a look at the operation of ThreadLocal. Take get as an example.

Public T get () {

/ / current thread Thread t = Thread.currentThread ();

/ / get the threadLocalMap of the current thread, that is, the map reference ThreadLocalMap map in the above figure = getMap (t)

If (map! = null) {

/ / get the Entry for which the current ThreadLocal is Key, and ThreadLocalMap.Entry e = map.getEntry (this) to prevent memory leaks

If (e! = null) {@ SuppressWarnings ("unchecked") T result = (T) e.value

Return result;}}

/ / if you set the default value for null return setInitialValue ();}

As shown in the source code of the get method above, when calling the threadLocal.get () method, threadLocal gets the entry corresponding to threadLocal itself as key in the ThreadLocalMap in the current thread, and handles memory leaks in this getEntry method. The processing logic is that if the Entry corresponding to threadLocal is null, let the value of this entry be null and the threadLocal in map correspond to null, otherwise call the default method setInitialValue ()

Private T setInitialValue () {T value = initialValue ()

Thread t = Thread.currentThread ()

ThreadLocalMap map = getMap (t)

If (map! = null) map.set (this, value)

Else createMap (t, value); return value;}

/ / default null implementation protected T initialValue () {return null;}

The logic of the setInitialValue () method is relatively simple, and there is not much detail here. It is worth noting that the initialValue () called in it does not have any implementation, so we usually choose to override this method when we use threadLocal.

/ / here the main method is tested, so decorating with static will prolong the life cycle of threadLocal, and there is a risk of memory leakage. Generally speaking, it is sufficient for public static ThreadLocal threadLocal = new ThreadLocal () {as a member variable.

@ Override protected String initialValue () {

Return "init string from initialValue method"

}}

Public static void main (String [] args) throws InterruptedException {

/ / call get System.err.println ("invoke get before any set:" + threadLocal.get ()) directly without putting value; threadLocal.set ("test")

System.err.println ("before thread start:" + threadLocal.get ())

New Thread (()-> {

/ / A pair of identical threadLocal objects put the value threadLocal.set ("test in thread")

System.err.println ("In thread [" + Thread.currentThread () .getName () + "] threadLocal value:" + threadLocal.get ());}) .start ()

TimeUnit.SECONDS.sleep (1)

/ / prove that value in threadLocal does not share System.err.println in threads ("after thread value:" + threadLocal.get ());}

Combining this Mini Program with the picture above, you can have a general understanding of threadLocal. Other methods such as set, remove and other methods are more or less the same, you can look at the source code combined with the picture, I will not repeat it here.

About memory leaks

1. In the get, set and remove methods of threadLocal, they all deal with possible memory leaks. It is also mentioned above that if the corresponding entry is null, the value is set to null and the corresponding subscript reference in map is set to null.

2. For the leakage of this object in threadLocal, it is implemented in the way of weak reference. In the figure above, I use dotted lines to represent the weak reference, which means that the reference will be reclaimed when JVM does garbage collection (regardless of whether there is enough memory or not). Imagine that if a strong reference is used and the reference in the stack disappears, the threadLocal object will not be recycled and inaccessible until the thread ends, resulting in a memory leak.

3. A brief overview of the four citations of Java

Weak references are mentioned above in ThreadLocal, and here are four references in Java, by the way.

Strong reference: refers to the object that comes out of new. Generally, objects that are not specifically stated are strong references. This kind of object is recycled only if GCroots cannot find it. Soft references (subclasses of SoftReference): only such referenced objects will be reclaimed if there is insufficient memory after GC. Weak reference (a subclass of WeakReference): objects with only this reference are recycled when GC (regardless of whether there is not enough memory). Virtual reference (PhantomReference subclass): there is no special function, like a tracker, in conjunction with the reference queue to record when the object is reclaimed. (in fact, all four references can be used with the reference queue, as long as the reference queue that needs to be associated is passed in the constructor, and it will be written to the queue when the object calls the finalize method.)

After reading the above, do you have any further understanding of how to analyze stack closure and ThreadLocal in java thread closure? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report