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 use the ThreadLocal class in Java

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "how to use ThreadLocal class in Java". In daily operation, I believe many people have doubts about how to use ThreadLocal class in Java. The editor 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 about "how to use ThreadLocal class in Java". Next, please follow the editor to study!

What is the use of Threadlocal:

To put it simply, an ThreadLocal is shared in one thread and isolated between different threads (each thread can only see its own thread's value). As shown below:

Introduction of ThreadLocal usage example API

Before using Threadlocal, let's take a look at its API:

The API of the ThreadLocal class is very simple, the more important here are get (), set (), remove (), set is used for assignment, get is used to get the value of the variable, and remove is to delete the value of the current variable. It is important to note that the initialValue method is triggered on the first call to initialize the value of the current variable, and initialValue returns null by default.

The use of ThreadLocal

After talking about the API of the ThreadLocal class, let's practice to understand the previous sentence: an ThreadLocal is shared in one thread and isolated between different threads (each thread can only see its own thread's value)

Public class ThreadLocalTest {private static ThreadLocal threadLocal = new ThreadLocal () {/ / override this method to modify the initial value of "thread variable". The default is null @ Override protected Integer initialValue () {return 0;}}. Public static void main (String [] args) throws InterruptedException {/ / Thread 1 new Thread (new Runnable () {@ Override public void run () {System.out.println ("Thread 1 before set:" + threadLocal.get ()); threadLocal.set (1) System.out.println ("after thread 1 set:" + threadLocal.get ());}}). Start (); / / thread 2 new Thread (new Runnable () {@ Override public void run () {System.out.println ("thread 2 before set:" + threadLocal.get () ThreadLocal.set (2); System.out.println ("after thread 2 set:" + threadLocal.get ());}}). Start (); / / main thread sleep 1s Thread.sleep (1000); / / main thread System.out.println ("thread value of main thread:" + thread ();}})

Explain the above code a bit:

Each ThreadLocal instance is similar to a variable name, and different ThreadLocal instances are different variable names, and they have a value (understood for the time being) that the "ThreadLocal variable or thread variable" in the later description represents an instance of the ThreadLocal class.

Create a static "ThreadLocal variable" in the class, create two threads in the main thread, and set the ThreadLocal variable to 1 and 2, respectively. Then wait for threads 1 and 2 to finish executing, and then look at the value of the ThreadLocal variable in the main thread.

Program results and Analysis of ⌛

The key point of the program result is that the output of the main thread is 0. if it is an ordinary variable, set the ordinary variable to 1 and 2 in thread 1 and thread 2, then print this variable after thread 1 and thread 2 has finished execution. the value of the output must be 1 or 2 (which output is related to the thread scheduling logic of the operating system). However, after assigning values through two threads using the ThreadLocal variable, the initial value of 0 is output in the main thread. This is why "an ThreadLocal is shared in one thread and isolated between different threads". Each thread can only see its own thread's value, which is the core role of ThreadLocal: to implement thread-wide local variables.

The principle of Source Code Analysis of Threadlocal

Each Thread object has a ThreadLocalMap, and when you create a ThreadLocal, the ThreadLocal object is added to the Map, where the key is ThreadLocal and the value can be of any type. This sentence may not be well understood just now, but we will understand it after reading the source code together.

Our previous understanding is that all references to constant values or reference types are stored in ThreadLocal instances, but they are not, which only gives us a better understanding of the concept of ThreadLocal variables. Storing a value to ThreadLocal is actually storing a value to ThreadLocalMap in the current thread object. ThreadLocalMap can be simply understood as a Map, and the key storing value to this Map is the ThreadLocal instance itself.

Source code

? In other words, the data that you want to store in the ThreadLocal is not actually stored in the ThreadLocal object, but is stored in a Map in the current thread as a key of this ThreadLocal instance, and the same is true when getting the value of ThreadLocal. This is why ThreadLocal can achieve isolation between threads.

Inner class ThreadLocalMap

ThreadLocalMap is the inner class of ThreadLocal and implements a set of Map structure ✨.

ThreadLocalMap attribute:

Static class Entry extends WeakReference k = e.get (); / / in one case, the current reference returns the value if (k = = key) {e.value = value; return } / / slot point is dropped by GC reset state if (k = = null) {replaceStaleEntry (key, value, I); return;}} / / slot point is empty set value tab [I] = new Entry (key, value) / / set the number of ThreadLocal int sz = + + size; / / there are no slots to clean and the number is greater than the load factor rehash if (! cleanSomeSlots (I, sz) & & sz > = threshold) rehash ();}

Introduction to ThreadLocalMap attributes:

Similar to ordinary Hashmap, it is stored in an array, but unlike the zipper method used by hashmap to resolve hash conflicts, ThreadLocalMap uses the open address method.

The initial capacity of the array is 16, and the load factor is 2. 3.

The key of the node node encapsulates WeakReference for recycling

ThreadLocalMap storage location

Stored in Thread, there are two ThreadLocalMap variables

ThreadLocals is created in the ThreadLocal object method set and maintained by ThreadLocal

Public void set (T value) {Thread t = Thread.currentThread (); ThreadLocalMap map = getMap (t); if (map! = null) map.set (this, value); else createMap (t, value);} void createMap (Thread t, T firstValue) {t.threadLocals = new ThreadLocalMap (this, firstValue);}

InheritableThreadLocals and ThreadLocal, like InheritableThreadLocal, rewrite the createMap method

Void createMap (Thread t, T firstValue) {t.inheritableThreadLocals = new ThreadLocalMap (this, firstValue);}

The function of inheritableThreadLocals is to pass ThreadLocalMap to child threads

Create a ThreadLocalMap for the child thread directly when the condition is met in the init method

Note:

Passing the inheritableThreadLocals variable that changes the child thread midway only when the child thread is initialized does not pass the result to the child thread.

When using a thread pool, you should pay attention to the fact that the thread is not recycled and try to avoid errors caused by the inheritableThreadLocals of the parent thread

The problem of weak reference in Key

Why use weak quotes? this is the official answer.

To help deal with very large and long-lived usages, the hash table entries use WeakReferences for keys.

To handle very large and very long-lived threads, the hash table uses weak references as key.

A thread with a long life cycle can be understood as the core thread of the thread pool.

When ThreadLocal does not have strong references to external objects, such as Thread, weak references Key will be recycled when GC occurs, while Value will not be recycled if strong references occur. If the thread that created ThreadLocal keeps running like threads in the thread pool, then the value in this Entry object may not be reclaimed all the time, resulting in memory leakage.

Key uses strong references to ThreadLocal objects that are recycled, but ThreadLocalMap also holds strong references to ThreadLocal, and if it is not manually deleted, ThreadLocal will not be recycled, resulting in Entry memory leaks.

Key objects that use weak references to ThreadLocal are recycled, and because ThreadLocalMap holds a weak reference to ThreadLocal, ThreadLocal is recycled even if it is not manually deleted. Value will be cleared the next time ThreadLocalMap calls set,get,remove.

Some optimizations have been made in Java8, for example, when the get (), set (), and remove () methods of ThreadLocal are called, the Value of all Entry in the thread ThreadLocalMap with Key as null will be cleared, and the entire Entry will be set to null, which is beneficial to the next memory collection.

Four references in java

Strong reference: if an object has a strong reference, it will not be reclaimed by the garbage collector. Even if the current memory space is insufficient, JVM does not reclaim it, but instead throws an OutOfMemoryError error, causing the program to terminate abnormally. If you want to break the association between a strong reference and an object, you can explicitly assign the reference to null, so that JVM will recycle the object at the appropriate time

Soft references: when using soft references, if there is enough memory, the soft reference can continue to be used without being reclaimed by the garbage collector, and only when there is insufficient memory will the soft reference be reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caching, such as web page caching, image caching, and so on. Using soft references can prevent memory leaks and enhance the robustness of the program)

Weak references: objects with weak references have a shorter life cycle. Because when JVM performs garbage collection, weak references will be reclaimed once weak reference objects are found, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a low-priority thread, weak reference objects may not be found quickly.

Virtual references do not determine the lifecycle of an object. If an object holds only a virtual reference, it can be reclaimed by the garbage collector at any time as if it had no reference at all. Virtual references must be used in conjunction with reference queues (ReferenceQueue). When the garbage collector is ready to recycle an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory. (note that other references are not passed into ReferenceQueue until they are recycled by JVM. Because of this mechanism, virtual references are mostly used to refer to the processing before destruction. You can use some operations before the object is destroyed, such as resource release, etc. )

Usually, the life cycle of ThreadLocalMap is as long as that of Thread (pay attention to Thread in thread pool). If the corresponding key is not manually deleted (the thread is returned to the thread pool after use, where the KV is no longer used but will not be recycled by GC, it can be considered as a memory leak), it will certainly lead to memory leakage, but the use of weak references can provide an additional layer of protection: weak references will be reclaimed by GC and will not leak memory. The corresponding value will be cleared the next time ThreadLocalMap calls set,get,remove, and Java8 has made the above code optimization.

At this point, the study on "how to use the ThreadLocal class in Java" is over. I hope to be able to solve your 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.

Share To

Development

Wechat

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

12
Report