[Interview Question] The underlying principles and usage scenarios of ThreadLocal

What is ThreadLocal?

ThreadLlocal is a thread local storage mechanism provided in Java. This mechanism can be used to cache data inside a thread. The thread Cached data can be obtained at any time and in any method.

You can take a look at a simple Demo:

public class ThreadLocalDemo {
    public static ThreadLocal<String> s = new ThreadLocal<>();

    public static void main(String[] args) {
		s.set("Harmony");
        String s1 = ThreadLocalDemo.s.get("");    
	}
}

ThreadLocal underlying principle

The bottom layer of Threadlocal is implemented through ThreadloalMap .

ThreadlocaMap exists in everyThread object (note that it is not ThreadLocal), < a i=4>Map key isThreadlocal object, Map value is the value that needs to be cached.  

We can clearly see that there is indeed a ThreadLocalMap in the ThreadLocal class as a static inner class, but its a> is used but is in the thread (inside Thread) !

We can take a look at its set() and get() methods 

// ThreadLocal类
public void set(T value) {
	Thread t = Thread.currentThread();
	ThreadLocal.ThreadLocalMap map = getMap(t);
	if (map != null)
		map.set(this, value);
	else
		createMap(t, value);
}
public T get() {
	Thread t = Thread.currentThread();
	ThreadLocal.ThreadLocalMap map = getMap(t);
	if (map != null) {
		ThreadLocal.ThreadLocalMap.Entry e = map.getEntry(this);
		if (e != null) {
			@SuppressWarnings("unchecked")
			T result = (T)e.value;
			return result;
		}
	}
	return setInitialValue();
}

Memory leak (thread pool)

If used inthread poolThreadLocal will cause Memory leak.

WhenThreadLocal object is used, the set key and value should be set (ie: Entry object) is recycled, but the thread in the thread pool will not Recycling, and the thread object is pointed to ThreadLocalMap. If the thread is not recycled, the Entry object will not be recycled, thus causing Memory leak! ! ! strong reference, ThreadLocalMap also points to the Entry object throughstrong reference

Solution

After using the ThreadLocal object, manually call ThreadLocal’s remove() method, manually clear the Entry object!

scenes to be used

The classic application scenario of Threadlocal isConnection management

A thread holds a connection, and theconnection object can be used indifferent methods the same connection. do not share are passed between threads, and threads

Guess you like

Origin blog.csdn.net/weixin_43715214/article/details/131733959