ThreadLocal memory leak

I saw an article about ThreadLocal memory leak on the Internet some time ago

Therefore, I also studied the ThreadLocal object. Its principle is:

The variable value defined by ThreadLocal will be stored in a map collection of the current thread

The map stores the entity object. The key of the entity object is the weak reference of the current ThreadLocal object,

Value is the value of the ThreadLocal variable

This raises a question:

If the strong reference of ThreadLocal variable is lost, the weak reference in the map will become invalid, and GC will recycle the ThreadLocal object

Then the value of ThreadLocal will remain in the map until the thread is recycled, but there is no way to obtain it because the key is released

In fact, the JDK handles this problem to a certain extent, that is, the entity with null key will be overwritten or cleared

Of course, we should also note that the following usages are problematic:

1. New multiple times for the same variable name

ThreadLocal a=new ThreadLocal();

.....

a=new ThreadLocal();

2. Local generation of variables

public void func(){

ThreadLocal a=new ThreadLocal();

}

or

for(int i=0;i<100;i++){

ThreadLoal b=new ThreadLocal();

}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>