当前位置:网站首页>Make a ThreadLocal (source code) that everyone can understand
Make a ThreadLocal (source code) that everyone can understand
2022-06-27 13:56:00 【Call me uncle】
Catalog
Two 、ThreadLocal And Synchronized The difference between
3、 ... and 、ThreadLocal analysis
Four 、ThreadLocal Source code analysis
5、 ... and 、ThreadLocal Data structure of
introduce :
We know that in our multithreading , If you access the same shared variable at the same time , There may be thread safety issues , To ensure thread safety , We often lock the shared variable when accessing it , To achieve synchronization .

May cause deadlock , So introduce ThreadLocal
1、ThreadLocal
ThreadLocal yes JDK Provided , Support thread local variables . in other words , If we create a ThreadLocal Variable , To access this variable Every thread Will have one of these variables Local copy . If multiple threads read and write to this variable at the same time , In fact, it is the thread itself that operates Local Variables in memory , Thus avoiding Thread safety The problem of .

- ThreadLocal Provides a thread local instance . It differs from ordinary variables in that , Each thread using this variable initializes a completely independent instance copy .ThreadLocal Variables are usually private static modification . When a thread ends , All that it uses ThreadLocal Relative instance copies can be recycled .
Two 、ThreadLocal And Synchronized The difference between
Common ground :
- ThreadLocal and Synchonized Are used to solve multithreaded concurrent access .
difference :
- Synchronized Used for inter thread communication Data sharing , and ThreadLocal Is used for inter thread Data isolation
- Synchronized It's using the lock mechanism , Make variables or code blocks accessible to only one thread at a time . and ThreadLocal For every one Threads provide copies of variables , So that each thread at a certain time access is not the same object , This isolates multiple threads from sharing data . and Synchronized But the opposite is true , It is used to obtain data sharing when communicating among multiple threads .
3、 ... and 、ThreadLocal analysis
initial

change : Add delete ThreadLocal Variable operations in

Threads A And thread B Stored in ThreadLocal The variables in do not interfere with each other , Threads A Stored variables can only be used by threads A visit , Threads B Stored variables can only be used by threads B visit .
Four 、ThreadLocal Source code analysis
Set() Method
public void set(T value) {
// Get the current thread
Thread t = Thread.currentThread();
// Take the current thread as Key, obtain ThreadLocalMap object
ThreadLocalMap map = getMap(t);
// Acquired ThreadLocalMap The object is not empty
if (map != null)
// Set up value Value
map.set(this, value);
else
// Acquired ThreadLocalMap The object is empty , establish Thread Class threadLocals Variable
createMap(t, value);
}
// there this It refers to calling... In the code set The object of , That is to say ThreadLocal object As you can see from the code above ,ThreadLocal set When assigning values, the current thread will be obtained first thread, And use the current thread as Key call getMap(t) Method thread In thread ThreadLocalMap attribute . If map Property is not empty , Then directly update value value , If map It's empty , Call the program createMap(t, value) Method to instantiate Thread Class threadLocals Member variables . That is, to create the current thread threadLocals Variable
- getMap()
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
getMap(Thread t) Method gets the value of the thread variable itself threadLocals Member variables - ThreadLocalMap ()
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;
}
}
}See ThreadLocalMap yes ThreadLocal The inner static class of , And its composition mainly uses Entry To save the data , And it's an inherited weak reference . stay Entry For internal use ThreadLocal As key, Use our settings value As value.
- createMap()
// This is threadlocal Internal method of
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
//ThreadLocalMap Construction method
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);
}get() Method
public T get() {
// Get the current thread
Thread t = Thread.currentThread();
// Gets the current thread's threadLocals Member variables
ThreadLocalMap map = getMap(t);
// Acquired threadLocals Variable is not empty
if (map != null) {
// Return the value corresponding to the local variable
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
// initialization threadLocals The value of the member variable
return setInitialValue();
}Get through the current thread threadLocals Member variables , If threadLocals The member variable is not empty , The local variable bound by the current thread is returned directly , Otherwise, call setInitialValue() Method initialization threadLocals The value of the member variable .
- etInitialValue()
private T setInitialValue() {
// Call initialization Value Methods
T value = initialValue();
Thread t = Thread.currentThread();
// According to the current thread threadLocals Member variables
ThreadLocalMap map = getMap(t);
if (map != null)
//threadLocals Not empty , Is set value value
map.set(this, value);
else
//threadLocals It's empty , establish threadLocals Variable
createMap(t, value);
return value;
}- initialValue()
protected T initialValue() {
return null;
}remove() Method
public void remove() {
// According to the current thread threadLocals Member variables
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
//threadLocals The member variable is not empty , The remove value value
m.remove(this);
}remove Method , Direct will ThrealLocal The corresponding value is different from the current value Thread Medium ThreadLocalMap Delete in . Why delete , This involves memory leaks .
actually ThreadLocalMap Used in key by ThreadLocal The weak references , The characteristic of weak citation is , If this object has only weak references , Then the next time the garbage is recycled, it will be cleaned up .
So if ThreadLocal Without strong external reference , It's going to be cleaned up when it's recycled , thus ThreadLocalMap Use this ThreadLocal Of key It's going to be cleaned up . however ,value Is a strong quote , Will not be cleaned up , In this way, there will be key by null Of value.
5、 ... and 、ThreadLocal Data structure of

- Weak reference
ThreadLocalMapHas its own independent implementation , You can simply put it inkeyRegard asThreadLocal,valueIs the value placed in the code ( actuallykeyNot at allThreadLocalIn itself , It's one of its Weak reference )
- Thread isolation
- Every thread is going to
ThreadLocalWhen you put value in , Will go to their ownThreadLocalMapLi Cun , Reading is also based onThreadLocalAs a quotation , In their ownmapFind the correspondingkey, So that Thread isolation .
- Every thread is going to
- structure
ThreadLocalMapIt's kind of similarHashMapStructure , It's justHashMapBy Array + Linked list Realized , andThreadLocalMapNot in China Linked list structure .
repair :Java Four reference types of
Strong citation : We often new The object that comes out is a strong reference type , As long as the strong reference exists , The garbage collector will never recycle the referenced object , Even when there's not enough memory
Soft citation : Use SoftReference Decorated objects are called soft references , The object pointed to by the soft reference is recycled when the memory is about to overflow
Weak reference : Use WeakReference Decorated objects are called weak references , As long as garbage collection occurs , If the object is only weakly referenced to , Then it will be recycled
Virtual reference : Virtual reference is the weakest reference , stay Java Use in PhantomReference Define . The only function of virtual reference is to use the queue to receive notification that an object is about to die
边栏推荐
- Rereading the classic: the craft of research (1)
- Redis持久化
- External memory
- MySQL 索引及其分类
- NAACL 2022 | TAMT:通过下游任务无关掩码训练搜索可迁移的BERT子网络
- [OS command injection] common OS command execution functions and OS command injection utilization examples and range experiments - based on DVWA range
- AXI總線
- The second part of the travel notes of C (Part II) structural thinking: Zen is stable; all four advocate structure
- 实现WordPress上传图片自动重命名的方法
- Acwing game 57
猜你喜欢
随机推荐
机械硬盘和ssd固态硬盘的原理对比分析
POSIX AIO -- glibc 版本异步 IO 简介
实现WordPress上传图片自动重命名的方法
CMOS级电路分析
crane:字典项与关联数据处理的新思路
CMOS level circuit analysis
Shell 简明教程
Crane: a new way of dealing with dictionary items and associated data
Embedded development: embedded foundation callback function
Is there any discount for opening an account now? Is it safe to open an account online?
海外仓知识科普
How ASP connects Excel
buuctf misc 百里挑一
Acwing game 57
现在开户有优惠吗?网上开户是否安全么?
隐私计算FATE-离线预测
打印输出数(递归方法解决)
[OS command injection] common OS command execution functions and OS command injection utilization examples and range experiments - based on DVWA range
How to solve the problem of missing language bar in win10 system
[PHP code injection] common injectable functions of PHP language and utilization examples of PHP code injection vulnerabilities





![[XMAN2018排位赛]通行证](/img/eb/7bf04941a96e9522e2b93859266cf2.png)

![[安洵杯 2019]Attack](/img/1a/3e82a54cfcb90ebafebeaa8ee1ec01.png)
