当前位置:网站首页>Brief introduction to ThreadLocal class
Brief introduction to ThreadLocal class
2022-07-28 08:03:00 【The galloping snail has been occupied】
ThreadLocal Construction method of
public ThreadLocal() {
}
set
public void set(T value) {
Thread t = Thread.currentThread();// Current thread
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);//this==》 At present threadLocal object ;
else
createMap(t, value);
}
Why? ThreadLocal It can save the private variables of each thread ?
because ThreadLocal Just equivalent to a tool key, In fact, the value is stored in the current thread ; Above set In the method , First, get the current thread t , And then use it getMap(t) , From the current thread t in , Get ThreadLocalMap object threadLocals; And then ThreadLocal Objects and value Value to key-val The form is preserved in ThreadLocalMap Of Entry in ;
get
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
get The process :
- 1. Get the current thread
- 2. Through the current thread , Get ThreadLocalMap The object of :threadLocals
- 3. from threadLocals Get in object ThreadLocal object , Find value :value;
ThreadLocalMap
set When it's worth it , In fact, what really saves value is ThreadLocalMap object ;
We can look at it ThreadLocalMap Source code :
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/** Initialize capacity size */
private static final int INITIAL_CAPACITY = 16;
/** Store entry Of table, And before HashMap Medium entry Different */
private Entry[] table;
/** Already stored entry Number */
private int size = 0;
/** table Threshold of capacity enlargement */
private int threshold;
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
ThreadLocalMap In the structure of 2 A key structure :
- Entry object , preservation ThreadLocal Object and variable values :value
- table Array , What's stored is Entry object ;
ThreadLocalMap Although it's called map, But with common HashMap Dissimilarity , Its structure is not : Array + Linked list / Array + Linked list + Red and black trees ;
It's just a table Array ; The objects stored in the array are Entry,Entry It's a key-value Structure ;
test
We know ThreadLocal Stored value ThreadLocalMap Is an array , Therefore, one thread can add multiple ThreadLocal object ;
ThreadLocal<String> threadLocal = new ThreadLocal<>();
ThreadLocal<String> threadLocal2 = new ThreadLocal<>();
Thread t1 = new Thread(()->{
threadLocal.set("1");
threadLocal2.set("threadLocal2 var2. ,,,,,,")
System.out.println("t1:"+threadLocal.get()+";threadLocal2 :"+threadLocal2 .get());});
Thread t2 = new Thread(()->{
threadLocal.set("2");
System.out.println("t2:"+threadLocal.get());});
Thread t3 = new Thread(()->{
threadLocal.set("3");
System.out.println("t3:"+threadLocal.get());});
t1.start();
t2.start();
t3.start();
Each thread can be based on its own situation , add to ThreadLocal Variable ; If there is 2 Variables need to be stored separately by threads , You can add 2 individual ThreadLocal object ; Can also be 2 Variables are packaged into a class , You only need one ThreadLocal It's OK to store ;
For example, when the browser requests the server , Each request corresponds to a request Object and a response object ; There is 2 There are ways to store
Mode one :
ThreadLocal<Request > request = new ThreadLocal<>();
ThreadLocal<Response > response = new ThreadLocal<>();
Mode two : Pack it up session class
public class Session{
Request request ;
Response response ;
}
ThreadLocal<Session> session= new ThreadLocal<>();
边栏推荐
- Pytorch的冻结以及解冻
- ASP. Net core technology insider and project practice after reading
- 辨析覆盖索引/索引覆盖/三星索引
- Awk from introduction to earth (16) discussion on the types of awk variables -- about the two types of numbers and strings
- How do we run batch mode in MySQL?
- DNA modified rhodium RH nanoparticles rhnps DNA (DNA modified noble metal nanoparticles)
- EMC rectification method set
- Autodesk desktop licensing service error 1067 handling method
- Qt使用信号量控制线程(QSemaphore)
- Will ordinary browsers disclose information? How to protect privacy by using a secure browser?
猜你喜欢

Delete the nodes in the linked list - daily question

Synthesis of dna-ag2sqds DNA modified silver sulfide Ag2S quantum dots

铜铟硫CuInSe2量子点修饰DNA(脱氧核糖核酸)DNA-CuInSe2QDs(齐岳)
![[event registration] cloud native technology exchange meetup, see you in Guangzhou on August 6](/img/08/b892bd6c14d5ba3691f9b7def29c35.png)
[event registration] cloud native technology exchange meetup, see you in Guangzhou on August 6

Use ffmpeg to generate single image + single audio streaming video in batches

DNA deoxyribonucleic acid modified platinum nanoparticles ptnps DNA | scientific research reagent

辨析覆盖索引/索引覆盖/三星索引

Discrimination coverage index / index coverage / Samsung index

Information system project manager must recite the core examination site (41) risk management plan

@The role of documented
随机推荐
解决CNN固有缺陷!通用 CNN 架构CCNN来了| ICML2022
DNA修饰贵金属纳米颗粒|DNA脱氧核糖核酸修饰金属钯Pd纳米颗粒PdNPS-DNA
辨析覆盖索引/索引覆盖/三星索引
Why is ESD protection so important for integrated circuits? How to protect?
ASP. Net core technology insider and project practice after reading
Opencv's practical learning of credit card recognition (4)
Mechanical revolution Jiaolong P wired network card driver can't play
C language explanation series - array explanation, one-dimensional array, two-dimensional array
登录模式:单一服务器模式、单点登录、token模式
Oracle local network service
How to analyze the taxi business problem of didi SQL interview question
Near infrared two region agzs quantum dots wrapped deoxyribonucleic acid dna|dna agzsqds (Qiyue)
Copper indium sulfide CuInSe2 quantum dots modified DNA (deoxyribonucleic acid) DNA cuinse2qds (Qiyue)
Swm32 series tutorial 5-adc application
【青鸟学员故事】追风少年“李晓亮”
What if the computer file cannot be deleted?
ArcGIS JS自定义Accessor,并通过watchUtils相关方法watch属性
Is the salary of test / development programmers unbalanced? Busy life, all kinds of job hopping
机械革命蛟龙p有线网卡驱动打不上
DNA modified osmium OS nanoparticles osnps DNA modified iridium nanoparticles irnps DNA