Learn the basics of multithreading -4.3 threadlocal when you use it

Source: Internet
Author: User

4.3 This section let's discuss some of the areas that need attention when it comes to the use of threadlocal.

Threadlocal main use is GET, set, InitialValue These methods, specific use we do not introduce here, the following is just to give some of its use when the need to pay attention to the place.

1. Null when the Get method is present
Package com.ray.deepintothread.ch04.topic_3; Public classThreadlocalgetnull {Private intCount =0; PublicThreadlocal<integer> intthreadlocal =NewThreadlocal<integer> (); Public int GetCount() {returnIntthreadlocal.Get(); } Public void Addcount() {intthreadlocal.Set(count++); } Public Static void Main(string[] args) {System. out. println (NewThreadlocalgetnull (). GetCount ()); }}

Output:
Exception in thread "main" java.lang.NullPointerException
At Com.ray.deepintothread.ch04.topic_3.ThreadLocalGetNull.getCount (threadlocalgetnull.java:10)
At Com.ray.deepintothread.ch04.topic_3.ThreadLocalGetNull.main (threadlocalgetnull.java:18)

Here the direct throw null pointer is abnormal, why? Because the implementation of threadlocal is achieved through map, I will introduce the implementation principle of threadlocal in the latter section.

For the above problem, our solution is: Use the InitialValue method when initializing.

Package com.ray.deepintothread.ch04.topic_3; Public classSolutionofthreadlocalgetnull {Private intCount =0; PublicThreadlocal<integer> intthreadlocal =NewThreadlocal<integer> () {//The solution is to initialize the values@OverrideprotectedIntegerInitialValue() {returnCount }    }; Public int GetCount() {returnIntthreadlocal.Get(); } Public void Addcount() {intthreadlocal.Set(count++); } Public Static void Main(string[] args) {System. out. println (NewSolutionofthreadlocalgetnull (). GetCount ()); }}

Output:
0

The returned value is initialized by the InitialValue method at the beginning of the definition threadlocal.

2.ThreadLocal Most of the time is used in multi-threaded situations, it is important to note that each thread is only calculated using a copy of the threadlocal label variable

Code Listing: (Here I follow an example of the previous chapter)

 PackageCom.ray.deepintothread.ch04.topic_3; Public  class threadlocaltest extends Thread {    Private intCount =0; PublicThreadlocal<integer> intthreadlocal =NewThreadlocal<integer> () {protectedIntegerInitialValue() {returnCount    }; }; Public int GetCount() {returnIntthreadlocal.get (); } Public void Addcount() {intthreadlocal.set (count++); }@Override     Public void Run() {Try{ for(inti =0; I <3;                i++) {addcount (); System.out.println ("thread["+ getName () +"] count["+ GetCount () +"]"); Sleep -); }        }Catch(Interruptedexception e)        {E.printstacktrace (); }    } Public Static void Main(string[] args)throwsinterruptedexception {NewThreadlocaltest (). Start (); Thread.Sleep ( -);NewThreadlocaltest (). Start (); Thread.Sleep ( -);NewThreadlocaltest (). Start (); }}

Output:
THREAD[THREAD-0] count[0]
THREAD[THREAD-0] count[1]
THREAD[THREAD-1] count[0]
THREAD[THREAD-0] count[2]
THREAD[THREAD-1] count[1]
THREAD[THREAD-1] count[2]
Thread[thread-2] count[0]
Thread[thread-2] count[1]
Thread[thread-2] count[2]

From the output we can see that the count value of each thread operation is independent and not affected by other threads.

Summary: In this chapter we discuss the two areas of attention used by threadlocal.

This chapter is here, thank you.

My github:https://github.com/raylee2015/deepintothread.

Catalog: http://blog.csdn.net/raylee2007/article/details/51204573

Learn the basics of multithreading -4.3 threadlocal when you use it

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.