Java ThreadLocal parsing

brief introduction

ThreadLocal is similar to local variables. It solves the problem that a single thread maintains the variable values (save, fetch, delete) in its own thread to isolate the data between threads. (inheritablethreadlocal special case)

Three classes are involved here: thread, ThreadLocal and threadlocalmap

Source code analysis

From the source code, we can see that the set, get and remove operations are threadlocalmap, the key is the current thread, and the value is the thread local variable cache value

public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this,value);
    else
        createMap(t,value);
}

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

public void remove() {
    ThreadLocalMap m = getMap(Thread.currentThread());
    if (m != null)
        m.remove(this);
}

ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

problem

Does not calling remove overflow memory? Not in most scenarios, only in a few.

When running, two references will be generated in the stack to point to the corresponding objects in the heap. It can be seen that threadlocalmap uses the weak reference of ThreadLocal as the key. In this way, if the strong reference between ThreadLocal ref and ThreadLocal is broken, that is, ThreadLocal ref is set to null, the ThreadLocal object is bound to be recycled in the next GC. In this way, entries with null keys will appear in threadlocalmap, and there is no way to access the values of these entries with null keys. If the current thread does not end again, such as using the thread pool, the thread will be put back into the thread pool after use and will not be destroyed, The values of these entries with null keys will always have a strong reference chain: thread ref - > thread - > threalocal map - > entry - > value can never be recycled, resulting in memory leakage.

reference material

https://www.cnblogs.com/dennyzhangdd/p/7978455.html Analysis of the ultimate source code of ThreadLocal https://liwx2000.iteye.com/blog/1774169 Will ThreadLocal overflow memory https://www.jianshu.com/p/cdb2ea3792b5 Deep understanding of Java weak references

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
分享
二维码
< <上一篇
下一篇>>