The underlying principle of ThreadLocal

(1) ThreadLocal is a thread local storage mechanism provided in Java, which can be used to cache data in a thread, and the thread can obtain cached data at any time and in any method.
(2) The bottom layer of ThreadLocal is implemented through ThreadLocalMap. There is a ThreadLocalMap in each Thread object (note that it is not a ThreadLocal object). The key of the Map is the ThreadLocal object, and the value of the Map is the value that needs to be cached.
(3) If ThreadLocal is used in the thread pool, it will cause a memory leak, because when the ThreadLocal object is used up, the key, value, or Entry object to be set should be recycled, but the threads in the thread pool will not be recycled, and The thread object points to the ThreadLocalMap through a strong reference, and the ThreadLocalMap points to the Entry object through a strong reference. If the thread is not recycled, the Entry object will not be recycled, resulting in a memory leak. The solution is to manually call the ThreadLocal after using the ThreadLocal object The remove method manually clears the object.
(4) The classic application scenario of ThreadLocal is connection management (a thread holds a connection, the connection object can be passed between different methods, and the threads do not share the same connection).
insert image description here

Guess you like

Origin blog.csdn.net/weixin_49131718/article/details/131795407