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 are the knowledge points of Java multithreaded ThreadLocal

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "what are the knowledge points of Java multithreaded ThreadLocal". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Application scenario

There are two common application scenarios for ThreadLocal:

In multithreaded concurrency scenarios, it is used to ensure thread safety.

When dealing with more complex business, use ThreadLocal instead of parameter display and transfer.

1.1. Ensure thread safety

Multi-thread access to the same shared variable is prone to concurrency problems, especially when multiple threads write to a variable, in order to ensure thread safety, general users need to take additional synchronization measures to ensure thread safety when accessing shared variables, such as locks such as synchronized, Lock and so on.

In addition to locking, ThreadLocal is a way to avoid thread unsafety in multithreaded access. When we create a variable, if each thread accesses it, it accesses the thread's own variable, so that there is no thread unsafe problem.

ThreadLocal is provided by the JDK package, which provides thread-local variables. If you create a ThreadLocal variable, each thread accessing the variable will have a copy of the variable. In the actual multithreaded operation, it operates on its own local memory variables, thus avoiding thread safety issues.

1.2. Display transfer parameters

Here are a few examples:

Example 1: get the current requesting user of the interface

In the whole process of the business logic of the background interface, if you need to obtain the information of the current requesting user in multiple places. A common practice is to obtain the current user information from session or token and store it in ThreadLocal by means of filter, interceptor, AOP and so on.

During the entire interface processing, if no additional thread is created, the current user can be obtained directly from the ThreadLocal variable without the need to authenticate and obtain the user from Session and token. This kind of scheme design not only improves performance, but also makes the originally complex logic and code simple and straightforward. For example, the following example:

(1) define the ThreadLocal variable: UserProfileThread.java

Public class UserProfileThread {private static ThreadLocal USER_PROFILE_TL = new ThreadLocal (); public static void setUserProfile (UserProfile userProfile) {USER_PROFILE_TL.set (userProfile);} public static UserProfile getUserProfile () {return USER_PROFILE_TL.get () } public static String getCurrentUser () {return Optional.ofNullable (USER_PROFILE_TL.get ()) .map (UserProfile::getUid) .orElse (UserProfile.ANONYMOUS_USER);}}

(2) set the variable value in the filter:

Override public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {UserProfile userProfile = null; / /. Verify and obtain user information userProfile UserProfileThread.setUserProfile (userProfile); filterChain.doFilter (servletRequest, servletResponse);}

(3) obtain current user information

/ / get the current user String uid=UserProfileThread.getCurrentUser (); / / get the current user object UserProfile user=UserProfileThread.getUserProfile ()

The sample 2:spring framework ensures that database transactions are executed under the same connection

If you want to implement jdbc transactions, you must operate in the same connection object. Under multiple connections, transactions will be uncontrollable and need to be completed with the help of distributed transactions. So how does the spring framework ensure that database transactions are executed under the same connection?

DataSourceTransactionManager is the data source transaction manager for spring. It fetches a connection from the database connection pool when you call getConnection (), binds it to ThreadLocal, and unbinds it when the transaction is complete. This ensures that the transaction is completed under the same connection.

two。 Realization principle

The ThreadLocal class provides the set/get method to store and obtain the value, but in fact, the ThreadLocal class does not store the value. The real storage depends on the ThreadLocalMap class.

Each thread instance corresponds to a TheadLocalMap instance. We can instantiate many ThreadLocal in the same thread to store many types of values. These ThreadLocal instances are used as key, corresponding to their own value, and finally stored in the Entry table array.

Let's take a look at ThreadLocal's set method:

Public class ThreadLocal {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 } void createMap (Thread t, T firstValue) {t.threadLocals = new ThreadLocalMap (this, firstValue);} / / omit other methods}

The logic of set is relatively simple, which is to get the ThreadLocalMap of the current thread and then add KV,K to the map. KV,K is the current ThreadLocal instance, and V is the value we passed in. It should be noted here that the acquisition of map needs to be taken from the Thread class object. Take a look at the definition of the Thread class.

Public class Thread implements Runnable {ThreadLocal.ThreadLocalMap threadLocals = null; / / omit other}

The Thread class maintains a variable reference to ThreadLocalMap.

Therefore, we can draw the following conclusions:

Each thread is an instance of Thread, and it internally maintains an instance member of threadLocals of type ThreadLocal.ThreadLocalMap.

The ThreadLocal itself is not a container, the value we access is actually stored in the ThreadLocalMap, and the ThreadLocal is just the key of the TheadLocalMap.

3. Matters needing attention

The ThreadLocal instance provides a remove () method to recycle the object and clear the corresponding memory footprint. This method is usually easily ignored, which leads to all kinds of problems. Such as the following:

Thread reuse: in the example of "get the current requesting user of the interface", the user's request is processed through the thread pool in Tomcat, while the thread in the thread pool is reused. It is certain that a thread will be reused by interfaces of different users, so the used ThreaLocal variables need to be overridden or cleared.

Memory overflow: because the life cycle of ThreadLocalMap is as long as that of Thread, if you create a large number of ThreadLocal variables, that is, the corresponding key takes up a lot of memory but is not manually deleted, it will lead to a memory leak to a certain extent.

This is the end of the content of "what are the knowledge points of Java multithreaded ThreadLocal". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Development

Wechat

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

12
Report