When and how should I use a ThreadLocal variable?

前端 未结 25 2310
再見小時候
再見小時候 2020-11-22 12:35

When should I use a ThreadLocal variable?

How is it used?

25条回答
  •  眼角桃花
    2020-11-22 13:10

    1. ThreadLocal in Java had been introduced on JDK 1.2 but was later generified in JDK 1.5 to introduce type safety on ThreadLocal variable.

    2. ThreadLocal can be associated with Thread scope, all the code which is executed by Thread has access to ThreadLocal variables but two thread can not see each others ThreadLocal variable.

    3. Each thread holds an exclusive copy of ThreadLocal variable which becomes eligible to Garbage collection after thread finished or died, normally or due to any Exception, Given those ThreadLocal variable doesn't have any other live references.

    4. ThreadLocal variables in Java are generally private static fields in Classes and maintain its state inside Thread.

    Read more: ThreadLocal in Java - Example Program and Tutorial

提交回复
热议问题