This article is a mirror article of machine translation, please click here to jump to the original article.

View: 27855|Reply: 1

[Source] Java ThreadLocal principles and multi-threaded reuse lead to data clutter

[Copy link]
Posted on 11/1/2021 11:45:36 AM | | | |
In programming, we define method parameters to pass variable content, if the execution method level is deep, then each method needs to define the parameters to be passed, at this time, some variables can be passed through ThreadLocal, as long as all methods are executed on the same thread, the value of ThreadLocal can be set and read.

The ThreadLocal class is used to provide local variables inside the thread. When these variables are accessed (get/set) in a multi-threaded environment, the variables in each thread are relatively independent of the variables in other threads.

ThreadLocal will first get the current thread (Thread t = Thread.currentThread()) when executing the set method, and use the current thread to get a ThreadLocalMap, if the map is not empty, it means that the current thread has a previously bound map, then update the value of this map, if not, use itself as the key to put the value in the map, so as to realize the binding of variables and threads.



Test the code, set the thread pool to maintain a maximum of 5 threads, and when we call the ThreadLocal get method in the case of multi-threading, we will get the ThreadLocal data (Data set by other threads), usThe ThreadLocal set method is not called on the current thread to set the data, as shown in the figure below:



Error causes:Once a thread is reused, it is likely that the first value obtained from ThreadLocal is a value left over from other previous threads

Because, after we finish with ThreadLocal on the current thread,Be sure to call remove for timely purge。 As shown below:



Code:

(End)





Previous:Docker looks at container restart settings and bulk stop containers
Next:Jenkins (5) Project group presentation
Posted on 11/2/2021 9:30:12 PM |
Come to learn again.
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com