当前位置:网站首页>ThreadLocal function, scene and principle
ThreadLocal function, scene and principle
2022-07-03 22:30:00 【Crazy DIU DIU DIU】
One 、ThreadLocal What is it?
- stay JDK 1.2 Available in java.lang.ThreadLocal,ThreadLocal It provides a new way to solve the concurrency problem of multithreaded programs . Using this tool class, you can write beautiful multithreaded programs very succinctly .
- ThreadLocal Not one Thread, It is Thread Local variables of
- stay JDK5.0 in ,ThreadLocal Generics are already supported , The class name of this class has changed to ThreadLocal.API The method has been adjusted accordingly , The new version of the API The methods are void set(T value)、T get() as well as T initialValue()
1、ThreadLocal The role of
ThreadLocal It's a good idea to solve the thread safety problem , It solves the conflict problem of variable concurrent access by providing an independent variable copy for each thread .ThreadLocal It's a good idea to solve the thread safety problem , It solves the conflict problem of variable concurrent access by providing an independent variable copy for each thread .
2、ThreadLocal Application scenarios of
stay Java In multithreading programming , To ensure the safe access of multiple threads to shared variables , You usually use synchronized To ensure that only one thread operates on shared variables at the same time . In this case, you can put class variables into ThreadLocal Object of type , Make variables have independent copies in each thread , When one thread reads a variable, it will not be modified by another thread . The most common ThreadLocal The usage scenario is used to solve the database connection problem 、Session Management etc. . Several scenarios will be cited below .
Two 、ThreadLocal Internal principle
ThreadLocal Several methods are provided in the class
//get() The method is to get ThreadLocal Copies of variables saved in the current thread
public T get() {
}
//set() Used to set the copy of variables in the current thread
public void set(T value) {
}
//remove() Used to remove copies of variables in the current thread
public void remove() {
}
//initialValue() It's a protected Method , It's usually used to rewrite in use , It is a delayed loading method
protected T initialValue(){
}
1、get Implementation of method source code
* Returns the value in the current thread's copy of this * thread-local variable. If the variable has no value for the * current thread, it is first initialized to the value returned * by an invocation of the {@link #initialValue} method. * * @return the current thread's value of this thread-local
*/
public T get() {
// Get the current thread
Thread t = Thread.currentThread();
// adopt getMap(t) Method to get a map,map The type of ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null) {
// Get <key,value> Key value pair , Note that the key value pairs passed in here are this, Instead of the current thread t
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
// If successful , Then return to value value
T result = (T)e.value;
return result;
}
}
// If map It's empty , Call setInitialValue Method returns value
return setInitialValue();
}
/** * Variant of set() to establish initialValue. Used instead * of set() in case user has overridden the set() method. * * @return the initial value */
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;
}
1.1、 have a look getMap(t) What did you do
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
// Call the current thread t, Returns the current thread t A member variable in threadLocals
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
1.2 Member variables threadLocals Source code
* ThreadLocalMap is a customized hash map suitable only for
* maintaining thread local values. No operations are exported
* outside of the ThreadLocal class. The class is package private to
* allow declaration of fields in class Thread. To help deal with
* very large and long-lived usages, the hash table entries use
* WeakReferences for keys. However, since reference queues are not
* used, stale entries are guaranteed to be removed only when
* the table starts running out of space.
*/
static class ThreadLocalMap {
/** * The entries in this hash map extend WeakReference, using * its main ref field as the key (which is always a * ThreadLocal object). Note that null keys (i.e. entry.get() * == null) mean that the key is no longer referenced, so the * entry can be expunged from table. Such entries are referred to * as "stale entries" in the code that follows. */
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
// Omit ....
}
It's actually a ThreadLocalMap, This type is ThreadLocal An inner class of a class , Let's continue to take a look at ThreadLocalMap The implementation of the
1.3 setInitialValue() Method 、createMap The implementation of the
setInitialValue() It's easy to understand , Is that if map Not empty , Just set the key value pair , It's empty , To create a Map, to glance at createMap The implementation of the
- createMap()
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
If you use ThreadLocal when , to get Before , Must first set, Otherwise, null pointer exception will be reported
public class ThreadLocalExsample {
ThreadLocal<Long> longLocal = new ThreadLocal<>();
public void set() {
longLocal.set(Thread.currentThread().getId());
}
public long getLong() {
return longLocal.get();
}
public static void main(String[] args) {
ThreadLocalExsample test = new ThreadLocalExsample();
// Be careful : No, set Before , direct get, newspaper null Abnormal
System.out.println("-------threadLocal value-------" + test.getLong());
}
}
3、 ... and 、ThreadLocal Application scenarios of
ThreadLocal Application scenarios of # Database connection
public Connection initialValue() {
return DriverManager.getConnection(DB_URL);
}
};
public static Connection getConnection() {
return connectionHolder.get();
}
ThreadLocal Application scenarios of # Session management
public static Session getSession() throws InfrastructureException {
Session s = (Session) threadSession.get();
try {
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
return s;
}
ThreadLocal Application scenarios of # Multithreading
* @Author Ann is very diligent in summer
* Create Date is 2019/3/21
*
* describe Java Medium ThreadLocal Class allows us to create variables that can only be read and written by the same thread .
* therefore , If a piece of code contains a ThreadLocal References to variables , Even if two threads execute this code at the same time ,
* They can't access each other's ThreadLocal Variable .
*/
public class ThreadLocalExsample {
/** * Created a MyRunnable example , And pass the instance as a parameter to two threads . Two threads execute run() Method , * And they're all there ThreadLocal Different values are saved on the instance . If they don't visit ThreadLocal Object and called set() Methods are synchronized , * Then the second thread will overwrite the value set by the first thread . however , Because they access a ThreadLocal object , * Therefore, neither thread can see the value saved by the other . in other words , They access two different values . */
public static class MyRunnable implements Runnable {
/** * Instantiated a ThreadLocal object . We only need to instantiate the object once , And there's no need to know which thread it's instantiated by . * Although all threads can access this ThreadLocal example , But each thread can only access itself by calling ThreadLocal Of * set() Value set by method . Even if two different threads are in the same ThreadLocal Different values are set on the object , * They still can't access each other's values . */
private ThreadLocal threadLocal = new ThreadLocal();
@Override
public void run() {
// Once you create a ThreadLocal Variable , You can set a value to be saved through the following code
threadLocal.set((int) (Math.random() * 100D));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
// You can read and save in ThreadLocal Values in variables
System.out.println("-------threadLocal value-------"+threadLocal.get());
}
}
public static void main(String[] args) {
MyRunnable sharedRunnableInstance = new MyRunnable();
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);
thread1.start();
thread2.start();
}
}
Running results
-------threadLocal value-------38
-------threadLocal value-------88
- Conclusion
ThreadLocal in set and get The operation is the corresponding thread table Array , So access the same... In different threads ThreadLocal Object's set and get Data access will not interfere with each other
Four 、 summary
- In each thread Thread There's a ThreadLocal.ThreadLocalMap A member variable of type threadLocals, This threadLocals It's used to store copies of actual variables , The key value is current ThreadLocal Variable ,value For variable copies ( namely T Variable of type )
- At the beginning , stay Thread Inside ,threadLocals It's empty , When passed ThreadLocal Variable call get() Methods or set() Method , Would be right. Thread Class threadLocals To initialize , And in the present ThreadLocal The variable is the key value , With ThreadLocal The copy variable type to be saved is value, Deposit in threadLocals. In the current thread , If you want to use a replica variable , You can go through get Method in threadLocals Look inside
- Actually pass ThreadLocal The created copy is stored in each thread's own threadLocals Medium
- threadLocals The type of ThreadLocalMap The key value of is ThreadLocal object , Because there can be more than one... Per thread threadLocal Variable
- It's going on get Before , Must first set, Otherwise, null pointer exception will be reported ; If you want to get You don't need to call set If you can visit normally , Must be rewritten initialValue() Method . Because in the above code analysis process , We found that if we didn't first set Words , That is to say map No corresponding storage can be found in , By calling setInitialValue Method returns i, And in the setInitialValue In the method , There is a statement that T value = initialValue(), By default ,initialValue Method returns null
边栏推荐
- Report on the current situation and development trend of ethoxylated sodium alkyl sulfate industry in the world and China Ⓞ 2022 ~ 2027
- Preliminary analysis of smart microwave radar module
- Pan Yueming helps Germany's Rochester Zodiac custom wristwatch
- How to switch between dual graphics cards of notebook computer
- Blue Bridge Cup Guoxin Changtian single chip microcomputer -- software environment (II)
- 2022 safety officer-a certificate registration examination and summary of safety officer-a certificate examination
- Blue Bridge Cup -- guess age
- Analysis report on the development prospect and investment strategy of global and Chinese modular automation systems Ⓟ 2022 ~ 2027
- [sg function]split game (2020 Jiangxi university student programming competition)
- DR-AP40X9-A-Qualcomm-IPQ-4019-IPQ-4029-5G-4G-LTE-aluminum-body-dual-band-wifi-router-2.4GHZ-5GHz-QSD
猜你喜欢

Exclusive interview with the person in charge of openkruise: to what extent has cloud native application automation developed now?

Code in keil5 -- use the code formatting tool astyle (plug-in)

This time, thoroughly understand bidirectional data binding 01

C deep anatomy - the concept of keywords and variables # dry inventory #

Take you to master the formatter of visual studio code

Farmersworld farmers world, no faith, how to talk about success?

540. Single element in ordered array
![Buuctf, web:[geek challenge 2019] buyflag](/img/02/d3add04f8145621bff35d46b82ba53.jpg)
Buuctf, web:[geek challenge 2019] buyflag

How can enterprises and developers take advantage of the explosion of cloud native landing?

The reason why the computer runs slowly and how to solve it
随机推荐
Overview of Yunxi database executor
SDNU_ ACM_ ICPC_ 2022_ Winter_ Practice_ 4th [individual]
DR-NAS26-Qualcomm-Atheros-AR9582-2T-2R-MIMO-802.11-N-5GHz-high-power-Mini-PCIe-Wi-Fi-Module
How to store null value on the disk of yyds dry inventory?
js demo 計算本年度還剩下多少天
string
js demo 计算本年度还剩下多少天
Label coco format data and format data in the upper left corner and lower right corner are mutually converted
Analysis report on the development trend and Prospect of global and Chinese supercontinuum laser source industry Ⓚ 2022 ~ 2027
1 Introduction to spark Foundation
Codeforces Round #768 (Div. 1)(A-C)
How does sentinel, a traffic management artifact, make it easy for business parties to access?
[dynamic programming] Jisuan Ke: Jumping stake (variant of the longest increasing subsequence)
How to solve the problem of computer networking but showing no Internet connection
Yyds dry goods inventory Prometheus alarm Art
Shell script three swordsman awk
Niuke winter vacation training camp 4 g (enumeration optimization, Euler power reduction)
The 14th five year plan for the construction of Chinese Enterprise Universities and the feasibility study report on investment Ⓓ 2022 ~ 2028
Quick one click batch adding video text watermark and modifying video size simple tutorial
LeetCode 1646. Get the maximum value in the generated array