Understanding threadlocal from the bottom why can one copy per thread

Source: Internet
Author: User
1. First, let us design this structure, how we design. Because threadlocal functionally, each thread has a separate copy, which is independent of each other, in its own stack. If we were to design it, we'd have to think of a relationship with each thread. Then each thread is associated with a specific value, which makes it easy for us to think of the HASHMAP data structure. Take thread as key, and value as we want. In multi-threading, we might think of thread-safe hashmap,concurrenthashmap this. However, Threadlocal is not the design, but it is very similar to the idea.
2. Let's take a look at the get and set methods of ThreadlocalPublic T get () {
Thread t = Thread.CurrentThread ();
Threadlocalmap map = getmap (t);
if (map! = null) {
Threadlocalmap.entry e = Map.getentry (this);
if (E! = null)
Return (T) E.value;
}
return Setinitialvalue ();
}

Private T Setinitialvalue () {
T value = InitialValue ();
Thread t = Thread.CurrentThread ();
Threadlocalmap map = getmap (t);
if (map! = null)
Map.set (this, value);
Else
Createmap (t, value);
return 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);
}

Why get a map by T? Instead of directly using a map. First, this map-specific variable entry inherits the WeakReference to help free up memory as soon as possible. Also because we see the map based on T.

The above is just my own understanding, if wrong, please understand.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.