当前位置:网站首页>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
边栏推荐
- Conditional statements of shell programming
- China's Call Center Industry 14th five year plan direction and operation analysis report Ⓔ 2022 ~ 2028
- C3p0 connection MySQL 8.0.11 configuration problem
- AST (Abstract Syntax Tree)
- The latest analysis of crane driver (limited to bridge crane) in 2022 and the test questions and analysis of crane driver (limited to bridge crane)
- To rotate 90 degrees clockwise and modify the video format
- How to obtain opensea data through opensea JS
- Es6~es12 knowledge sorting and summary
- 2022 electrician (elementary) examination questions and electrician (elementary) registration examination
- Summary of basic knowledge of exception handling
猜你喜欢

Teach you to easily learn the type of data stored in the database (a must see for getting started with the database)

Cesium terrain clipping draw polygon clipping

Pan Yueming helps Germany's Rochester Zodiac custom wristwatch

Pooling idea: string constant pool, thread pool, database connection pool

Leetcode: a single element in an ordered array

Bluebridge cup Guoxin Changtian single chip microcomputer -- detailed explanation of schematic diagram (IV)
![[Android reverse] application data directory (files data directory | lib application built-in so dynamic library directory | databases SQLite3 database directory | cache directory)](/img/b8/e2a59772d009b6ee262fb4807f2cd2.jpg)
[Android reverse] application data directory (files data directory | lib application built-in so dynamic library directory | databases SQLite3 database directory | cache directory)

Take you to master the formatter of visual studio code

6.0 kernel driver character driver

Wisdom tooth technology announced that it had completed the round D financing of US $100million and had not obtained a valid patent yet
随机推荐
[automation operation and maintenance novice village] flask-2 certification
Buuctf, misc: sniffed traffic
Development mode and Prospect of China's IT training industry strategic planning trend report Ⓣ 2022 ~ 2028
STM32 multi serial port implementation of printf -- Based on cubemx
Yyds dry goods inventory hands-on teach you to create a jigsaw puzzle using the canvasapi
On my first day at work, this API timeout optimization put me down!
The latest analysis of R1 quick opening pressure vessel operation in 2022 and the examination question bank of R1 quick opening pressure vessel operation
string
Oil monkey plug-in
How to store null value on the disk of yyds dry inventory?
Overview of Yunxi database executor
China's coal industry investment strategic planning future production and marketing demand forecast report Ⓘ 2022 ~ 2028
Code in keil5 -- use the code formatting tool astyle (plug-in)
How to connect a laptop to a projector
6.2 normalization 6.2.5 third normal form (3NF)
Unique in China! Alibaba cloud container service enters the Forrester leader quadrant
Mysql database - Advanced SQL statement (I)
Programming language (2)
To rotate 90 degrees clockwise and modify the video format
Harbor integrated LDAP authentication