Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the basic definition of ThreadLocal

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

In this issue, the editor will bring you what is the basic definition of ThreadLocal. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Basic definition and interpretation

Official interpretation: http://docs.oracle.com/javase/8/docs/api/

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g.a user ID or Transaction ID).

First, each thread has a local independent copy of the variable to ensure that the data between threads does not affect each other.

You can implement the default initial value of ThreadLocal by overriding the initialValue () method

Protected static final ThreadLocal TL_EXAMPLE = new ThreadLocal () {@ Override protected String initialValue () {return "default";}}

Why is it recommended that the description be defined as a static static method? Students who do not understand the principle of ThreadLocal may be confused, since it is necessary to meet multithreaded concurrency, how can it be defined as a static class member variable?

As long as you look at the source code of ThreadLocal, it has a static inner class called ThreadLocalMap. This Map is defined as a class member variable in the Thread class, that is, there is an independent copy of ThreadLocalMap in each Thread thread, and its value can only be read and modified by the current thread.

Imagine that multiple ThreadLocal variables are defined in a class, and the corresponding copy of the variable is obtained through ThreadLocalMap.get (ThreadLocal) in the current thread.

So the ThreadLocal variable itself is not a copy, you can think of it as a proxy, while the ThreadLocalMap stores a copy of the thread in the thread, and ThreadLocal is just a weak reference Key within the ThreadLocalMap (you can clean up the ThreadLocalMap in time when the ThreadLocal object fails).

This also answers why ThreadLocal can be defined as static, which is just a Key in Map, and there is no conflict between Map copies of different threads getting the same Key value.

Class ThreadLocal: public 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 ();} / * * ThreadLocalMap is a customized hash map suitable only for * maintaining thread local values. No operations are exported * outside of the ThreadLocal class. The class is package private to * allow declaration of fields in class Thread. To help deal with * very large and long-lived usages, the hash table entries use * WeakReferences for keys. However, since reference queues are not * used, stale entries are guaranteed to be removed only when * the table starts running out of space. * / static class ThreadLocalMap {...} class Thread: / * ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. * / ThreadLocal.ThreadLocalMap threadLocals = null;Thread1: ThreadLocalMap1: Thread2: ThreadLocalMap2:

It goes on to raise the question: is the ThreadLocal class itself thread-safe?

From the source code, we can see that neither get,set nor createMap do any synchronization or concurrent locking. The answer is safe because the implementation is based on the current thread.

Thread pool and initialization of ThreadLocal variables

In the case of thread pool reuse, if the ThreaLocal data is not cleaned up, it will be reused by later requests and get the value you modified!

Previously, I encountered a similar problem when implementing the log context LogContext:

Request An enters Controller, and a large number of values of ThreadLocal intermediate variables are recorded in the open thread Aline LogContext. After the request response is completed, request thread A returns to the thread pool.

When request B enters the Controller, the multiplexing thread Aline LogContext will continue to add information based on the value of the previous variable, so the log information becomes superimposed.

Be careful whether it's based on your own thread pool or on an application server such as Tomcat!

The standard or specification is to remove it after the thread variable has been used, or by calling threadLocalVariable.remove () in the finally code block to prevent it from being reused by other threads.

This is the basic definition of ThreadLocal shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report