In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "the example introduction of Java thread closure". In the daily operation, I believe that many people have doubts about the example introduction of java thread closure. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "Java thread closure example introduction"! Next, please follow the editor to study!
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 in the above figure ThreadLocalMap map = getMap (t); if (map! = null) {/ / get the Entry corresponding to the current ThreadLocal Key, in which ThreadLocalMap.Entry e = map.getEntry (this) is used to prevent memory leakage If (e! = null) {@ SuppressWarnings ("unchecked") T result = (T) e.value; return result;}} / / if the default value is set 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 () {@ Override protected String initialValue () {return "init string from initialValue method";}} as a member variable. Public static void main (String [] args) throws InterruptedException {/ / call get System.err.println directly ("invoke get before any set:" + threadLocal.get ()); 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.)
At this point, the study of "Java thread closure example introduction" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.