How to use ThreadLocal in Java
This article will explain in detail how to use ThreadLocal in Java, the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.
Start with the source code
First, let's take a look at the introduction in the ThreadLocal class: > This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g.a user ID or Transaction ID). Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).
As described in this article, ThreadLocal provides thread-local variables, and each thread has a separate copy, often in the form of private static variables. The key is that in the next segment, the thread survives, the ThreadLocal instance can be accessed, the thread disappears, and it will be garbage collected.
Get () method
See here, do you think of the reference type mentioned in the previous article, it may be soft reference or weak reference, what exactly is it? Or take a look at the code:
Public T get () {/ / get the current thread Thread t = Thread.currentThread (); / / get map ThreadLocalMap map = getMap (t) in the thread; if (map! = null) {ThreadLocalMap.Entry e = map.getEntry (this) If (e! = null) {@ SuppressWarnings ("unchecked") T result = (T) e.value; return result;}} return setInitialValue ();} ThreadLocalMap getMap (Thread t) {return t.threadLocals;}
The get () method in ThreadLocal is shown above, and the key map is the threadLocals variable in the Thread class. Let's continue to look at the source code of ThreadLocalMap:
ThreadLocal.ThreadLocalMap threadLocals = null; static class ThreadLocalMap {static class Entry extends WeakReference