This article reproduces the blog from the small Wolf
Preface
In the interview session, the investigation "ThreadLocal" is also the interviewer's routine, so it is very necessary to understand it thoroughly.
Some interviewers will come straight to the question:
"Do you know threadlocal?" ”
"Tell me about your understanding of threadlocal."
Of course, there are also interviewers will slowly lead to this topic, such as asking questions "in a multi-threaded environment, how to prevent their own variables to be tampered with other threads," the initiative to you, the rest on their own play.
So what threadlocal can do, before we know its application scenario, let's look at its implementation principle, only know the implementation principle, just to determine whether it conforms to its own business scenario. What is threadlocal?
First, it is a data structure, a bit like HashMap, can save "key:value" key value pairs, but a threadlocal can only save one, and the data of each thread do not interfere with each other.
threadlocal<string> localname = new ThreadLocal ();
Localname.set ("Account for the Little Wolf");
String name = Localname.get ();
Thread 1 Initializes a Threadlocal object LocalName, and through the set method, save a value for the small wolf, while thread 1 through the Localname.get () can get the previously set value, but if the thread 2, the get will be a null.
This is why, how it is implemented. But previously, threadlocal ensured that the data of each thread did not interfere with each other.
Look at the source code for set (T value) and get () methods
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;