当前位置:网站首页>Principle analysis of ThreadLocal source code

Principle analysis of ThreadLocal source code

2022-06-25 15:59:00 Favorite grapes

What( What is? ThreadLocal)

Commonly known as thread local variables , Is a method that can be used in the current thread , Just get The value set by this thread Tools for .

Like a string ,A The thread is set “abc”,B The thread is set “def”, When you want two threads to read again , Namely ,A Read “abc”,B Read yes “def”.

Why( Why use it ?)

Want different threads , Use the same variable , But the values read through it are the values set by each .

How( How to use it? ?)

ThreadLocal<String> tl = new ThreadLocal<>();

// thread1
tl.set("abc");
sout(tl.get()); // abc

// thread2
tl.set("def");
sout(tl.get()); // def

ThreadLocal How to do it ?

1、 Simply create one ThreadLocal Objects are useless . Only called set() perhaps get() When the method is used ,ThreadLocal It's just starting to work .
2. from set Speaking of , When we call set When the method is used ,ThreadLocal Internal will get the current Thread One inside threadLocals object , And its essence is ThreadLocalMap( A custom HashMap, There's a... In it Entry Array ,Entry Inherited from WeakReference,Entry Added a value attribute , Used to store values )
3. ThreadLocal<?> As Entry Value of weak reference , Is equivalent to HashMap Of Key.
4. So when you call get perhaps set When the method is used , It will go to the current thread threadlocals Read or set the corresponding value in .

ThreadLocalMap And traditional HashMap The difference between ?

It has only one array inside , When hash collision occurs , Will get the next array index , Instead of using the zipper method to create a linked list from the back . So his architecture , It's more like an array , Only the index value is through hash The algorithm determines .

A less elegant drawing illustrates :

 Insert picture description here

原网站

版权声明
本文为[Favorite grapes]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202190538057111.html