ThreadLocal implementation principle

ThreadLocal implementation principle

Answer: When using ThreadLocal to maintain variables, Threadlocal provides an independent copy of the variable for each thread that uses the variable, and each thread can independently change its own copy without affecting other threads' variable copies.

Each thread Thread has a  ThreadLocal.ThreadLocalMap member that holds thread-related variables.

 

Multiple ThreadLocal objects (tool classes) can be new in a thread , and the Entry array stores key-value pairs with each ThreadLocal object as the key .


Use WeakReference : when ThreadLocal has no strong reference, the entry with ThreadLocal as the key

All should be recycled, because the value in the entry cannot be obtained . If a strong reference is used, ThreadLocal cannot be recycled during the thread life cycle. When a weak reference is used, ThreadLocal will be automatically recycled by gc , even if the thread still exists ( for a long time ). thread ) .

ThreadLocal memory leak : When ThreadLocal has no strong reference, ThreadLocal is automatically reclaimed by gc . At this time, key=null, but value is not released. Only in get , set , and remove , the entry with key=null will be cleared .


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325642592&siteId=291194637