当前位置:网站首页>Analysis of ThreadLocal
Analysis of ThreadLocal
2022-06-23 02:13:00 【Pen head】
Deepen understanding ThreadLocal Words , May have a look Go into the details ThreadLocalMap
One 、ThreadLocal What is it?
ThreadLocal It's a tool , Can operate the current thread ThreadLocalMap data ,ThreadLocalMap Data cannot cross threads , It provides a new way to solve the concurrency problem of multithreaded programs .
Two 、ThreadLocal Use
Sometimes we don't want the values in the current thread to be modified by other threads . The following examples may not accurately express ideas , Mistakenly spray ..
public int TestValue=0;
public static void main(String[] args) {
Test test=new Test();
System.out.println(" Current thread value "+test.TestValue);
test.updateValue();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" Current thread value "+test.TestValue);
}public void updateValue(){
Thread T1=new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" New Threads Before the change value "+TestValue);
TestValue=1;
System.out.println(" New Threads After modification value :"+TestValue);
}
});
T1.start();
}We can get the following output
We can see that the new thread changes TestValue After value , The current thread is affected .
If we use ThreadLocal Variable , Will such behavior affect the use of our program ? Let's see
public ThreadLocal<Integer> TestLocalValue2=new ThreadLocal<>();
public static void main(String[] args) {
Test test=new Test();
test.TestLocalValue2.set(0);
System.out.println(" Current thread value "+test.TestLocalValue2.get());
test.updateThreadLocalValue();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" Current thread value "+test.TestLocalValue2.get());
}
public void updateThreadLocalValue(){
Thread T1=new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" New Threads Before the change value "+TestLocalValue2.get());
TestLocalValue2.set(1);
System.out.println(" New Threads After modification value "+TestLocalValue2.get());
}
});
T1.start();
}We can get the following output
We can find out ,
1. New thread modification ThreadLocal Variable data , The current thread is not affected
2. The new thread cannot get the current thread ThreadLocal Variable data , New thread modification ThreadLocal Before the variable , The data is null.
3、 ... and 、 A rough description of the source code
Let's see get What is done in the method
public T get() {
Thread t = Thread.currentThread(); // Get the current thread
ThreadLocalMap map = getMap(t);// Get... In this thread ThreadLocalMap data
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);// Get the current thread ThreadLocal by key Of Entry data
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();// establish ThreadLocalMap At the same time return to null
}ThreadLocalMap getMap(Thread t) { //t Is the current thread
return t.threadLocals; // The default initial value is null
}private T setInitialValue() {
T value = initialValue(); // Default initial value null
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value); // establish ThreadLocalMap
return value; // return null
}void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}get The general process of the method is
1. Get the current thread , Find the current thread ThreadLocalMap data
2. If ThreadLocalMap Not for null, And there's data , Then return data .
3. If ThreadLocalMap Not for null, But there's no data , Then put null Add to ThreadLocalMap in , At the same time return to null.
4. If ThreadLocalMap by null, Create ThreadLocalMap, At the same time return to null.
Let's see set Method
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}The general process is
1. Get the current thread , Find the current thread ThreadLocalMap data .
2. If ThreadLocalMap Not for null, Add data to ThreadLocalMap in .
3. If ThreadLocalMap by null, Create ThreadLocalMap.
We can see ThreadLocal The core of it is ThreadLocalMap.ThreadLocal The bottom layer of data operation is composed of ThreadLocalMap Accomplished . Let's see ThreadLocalMap structure
private static final int INITIAL_CAPACITY = 16;// Initial capacity —— Must be 2 The dark private Entry[] table;// Storing data table private int size = 0;// In an array entrys The number of , Can be used to judge table Whether the current usage exceeds the negative factor private int threshold; // Default to 0 Threshold for capacity expansion , When the usage of the table is greater than it, the capacity will be expanded
Entry Storage structure
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}Entry Inherit WeakReference, Using weak references , Can be ThreadLocal Object life cycle and thread life cycle unbound , Hold the right ThreadLocal The weak references , You can make ThreadLocal It is recycled when there are no other strong references , In this way, it can avoid that the thread cannot be destroyed , Lead to ThreadLocal Object cannot be recycled .
Four 、 Simple summary
The whole process is not complicated . It mainly involves three subjects ,Thread、TheadLocalMap、TheadLocal. Let's draw a diagram to see
TheadLocal Medium get、set Method is actually calling the current thread Thread in TheadLocalMap Of get、set Method , Yes Entry Arrays perform various operations . meanwhile TheadLocal yes Entry Medium key.
The above is right TheadLocal Simple understanding , Yes TheadLocal Deepen understanding , May have a look Go into the details ThreadLocalMap
边栏推荐
- Bc116 xiaolele changed to digital
- Data analysis method - user group analysis
- Interviewer: with the for loop, why do you need foreach??
- Muduo simple usage
- Exercise analysis summary
- How are pub and sub connected in ros1?
- JS rotation chart (Netease cloud rotation chart)
- Special exercise split line-----------------------------
- //1.15 putchar function
- Get the structure of the class through reflection, little chestnut
猜你喜欢

Data analysis method - user group analysis

1. Mx6u image burning principle (no specific process)

Ansible practice of Nepal graph

Branch and loop statements (including goto statements) -part1

1. introduction to MySQL database connection pool function technology points

Quick sorting C language code + auxiliary diagram + Notes

JS advanced part
![Buuctf misc-[bjdctf2020] Nani](/img/4e/ac6bf2f64cb68136581814da73db66.jpg)
Buuctf misc-[bjdctf2020] Nani

Anaconda creates a new environment encounter pit

Nebula operator cloud practice
随机推荐
Three ways to get class
WM view of commodity master data in SAP retail preliminary level
Error in OpenCV image operation: error: (-215:assertion failed)_ src. empty() in function ‘cv::cvtColor‘
Digital circuit logic design
Freshman C language summary post (hold change) Part 2 formatted monthly calendar
1. Mx6u bare metal program (5) - external interrupt
//1.9 char character variable operation
Pywebio to quickly build web applications
Deep learning environment configuration (I) installation of CUDA and cudnn
Performance testing -- Interpretation and practice of 16 enterprise level project framework
Nebula operator cloud practice
How are pub and sub connected in ros1?
Stop automatically after MySQL starts (unable to start)
//1.16 getchar function
1. Mx6u image burning principle (no specific process)
Google account cannot be logged in & external links cannot be opened automatically & words with words cannot be used
8 vertical centering methods
How to make word notes beautiful
Primary pointer part
OVS port traffic statistics practice