Use of threadlocal

Source: Internet
Author: User

Familiar with the looper source of friends may know, looper and thread binding is not directly set in, but through threadlocal this thing indirectly to the looper of the reference to the current thread hold.

Looper.java

private static void Prepare (Boolean quitallowed) {
if (sthreadlocal.get () = null) {
throw new RuntimeException ("Only one Looper could be created per thread");
}
Sthreadlocal.set (New Looper (quitallowed));
}


Threadlocal,java

public void Set (T value) {
Thread t = Thread.CurrentThread ();
Threadlocalmap map = getmap (t);
if (map! = null)
Map.set (this, value);
Else
Createmap (t, value);
}

Threadlocalmap Getmap (Thread t) {
return t.threadlocals;
}

As you can see, a threadlocalmap is maintained in each thread, and this map is used by this thread to store external resource objects. The added process is done by threadlocal such an intermediary, and the threadlocal is stored as a key in Threadlocalmap.

The advantage of this is that a map is maintained in each thread, so the same threadlocal is used, but different values are taken, which solves the problem of thread sharing resources.

So threadlocal is another way to solve shared resources, "take space for Time", while sysnchrozied is "change space".

Use of threadlocal

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.