ThreadLocal (middle) --- ThreadLocal underlying principle and memory leak analysis

Do you understand ThreadLocal?

Where is the ThreadLocal application scenario?

Do you know that ThreadLocal will cause a memory leak?


Each layer method in the same thread must be the same connection to support the transaction. After
Insert picture description here
Insert picture description here
one thread sets the object in ThreadLocal, another thread cannot get the object—
Insert picture description here
the set method of thread isolation ThreadLocal , the key in ThreadLocalMap is the threadLocal object itself , Value is the parameter value passed in:
Insert picture description here
Insert picture description here
tl.set(new Person()): Get the current thread, tl as the key, new Person() as the value, and put it in the map specific to the current thread

How to set it specifically: that is, a new Entry is stored.
Insert picture description hereInsert picture description hereInsert picture description here
Entry is a subclass of WeakReference, and the parent class's construction method is called when constructing; the parent class's construction method is to new a weak reference WR, and then pass k to it, k Is the tl object; weak reference WR points to tl

------I heard it for 73:44 seconds, the next time I continue
Insert picture description here
as shown above, the key pointing to threadLocal is a weak reference, so when the tl reference to threadLocal is cancelled, that is, when tl=null, only one key is left pointing to A weak reference to threadLocal, so that ThreadLocal can be recycled by the garbage collector, and the threadLocal pointed to by the key will not cause memory leaks

But
Insert picture description here
as shown in the figure above, when the key becomes null, the area pointed to by value cannot be recycled, resulting in a memory leak

Therefore, when you don’t use a key, value pair, remove it to prevent memory leaks


The get and set methods of threadlocal will remove the null key first, but still have to manually remove it-because many threads often do not execute the get and set methods for a long time


Insert picture description here
If it is a thread pool, the thread is used up and put back, threadlocal forgets to remove; next time this thread is taken out, but not cleaned up, and put back again, then threadlocal objects will accumulate and memory leaks will become more and more serious

Guess you like

Origin blog.csdn.net/nikyae/article/details/110913891