Solve the problem of memory leak and data loss in ThreadLocal

https://blog.csdn.net/qunqunstyle99/article/details/94717256

One thing to note here is:

We know that when using ThreadLocal, we must first new it, as follows:

    public static void main(String[] args) throws InterruptedException {
    
    
        ThreadLocal<String> threadLocal= new ThreadLocal();

        tl1(threadLocal);
        Thread.sleep(1000);
        tl2(threadLocal);

    }

    public static void tl1(ThreadLocal<String> threadLocal){
    
    
        threadLocal.set("xx");
    }

    public static void tl2(ThreadLocal<String> threadLocal){
    
    
        System.out.println(threadLocal.get());
    }

In fact, after we save it and take it out elsewhere, this strong reference to new exists.
Therefore, within this time range, ThreadLocal will not be recycled.

When we use the code, after removing the strong reference:

threadLocal = null;

When a GC occurs, the object pointed to by threadLocal will be recycled, even if the weak reference in the thread points to the new obj, it is useless

However, from the actual scenario, we removed the strong reference ourselves, and there must be no way to call the get method to get the value through it later.

In fact, there is no business data loss.

However, if we write threadLocal = null; code, it will cause memory leaks
when GC will take away our new ThreadLocal object, but its value has not been taken away.
Therefore, memory leaks

Therefore, when we do not need this ThreadLocal, we must actively release the resource, call the remove method, and
remove it from the thread memory

Of course, if the thread itself terminates, the ThreadLocal variable inside the thread can also be clear

Guess you like

Origin blog.csdn.net/Brave_heart4pzj/article/details/114983497