当前位置:网站首页>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
边栏推荐
- Blue Bridge Cup Guoxin Changtian single chip microcomputer -- led lamp module (V)
- Druids connect to mysql8.0.11
- webAssembly
- Codeforces Round #768 (Div. 1)(A-C)
- The 14th five year plan and investment feasibility study report of China's industry university research cooperation Ⓧ 2022 ~ 2028
- Blue Bridge Cup Guoxin Changtian MCU -- program download (III)
- Development trend and market demand analysis report of China's energy storage battery industry Ⓩ 2022 ~ 2028
- China HDI market production and marketing demand and investment forecast analysis report Ⓢ 2022 ~ 2028
- regular expression
- Data consistency between redis and database
猜你喜欢
Meta metauniverse female safety problems occur frequently, how to solve the relevant problems in the metauniverse?
The overseas listing of Shangmei group received feedback, and brands such as Han Shu and Yiye have been notified for many times and received attention
Unique in China! Alibaba cloud container service enters the Forrester leader quadrant
Redis single thread and multi thread
Overview of Yunxi database executor
320. Energy Necklace (ring, interval DP)
Blue Bridge Cup -- Mason prime
Buuctf, web:[geek challenge 2019] buyflag
Harbor integrated LDAP authentication
Summary of fluent systemchrome
随机推荐
[Android reverse] use the DB browser to view and modify the SQLite database (copy the database file from the Android application data directory | use the DB browser tool to view the data block file)
Development mode and Prospect of China's IT training industry strategic planning trend report Ⓣ 2022 ~ 2028
Learning notes of raspberry pie 4B - IO communication (SPI)
Report on the development status and investment planning trends of China's data center industry Ⓡ 2022 ~ 2028
Development trend and market demand analysis report of China's energy storage battery industry Ⓩ 2022 ~ 2028
LeetCode 1646. Get the maximum value in the generated array
Awk getting started to proficient series - awk quick start
Oil monkey plug-in
Cesium terrain clipping draw polygon clipping
Is the account opening of Guotai Junan Securities safe and reliable? How to open Guotai Junan Securities Account
The 2022 global software R & D technology conference was released, and world-class masters such as Turing prize winners attended
SDNU_ ACM_ ICPC_ 2022_ Winter_ Practice_ 4th [individual]
Overview of Yunxi database executor
JS Demo calcule combien de jours il reste de l'année
3 environment construction -standalone
Leetcode week 4: maximum sum of arrays (shape pressing DP bit operation)
[Android reverse] application data directory (files data directory | lib application built-in so dynamic library directory | databases SQLite3 database directory | cache directory)
[sg function]split game (2020 Jiangxi university student programming competition)
[dynamic planning] counting garlic customers: the log of garlic King (the longest increasing public subsequence)
js demo 计算本年度还剩下多少天