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

How to understand the thread local variable ThreadLocal of java

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

Share

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

This article introduces you how to understand the java thread local variable ThreadLocal, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Introduction

ThreadLocal, as a class under a java.lang package since JDK1.2, is very important in interviews and projects. The main purpose of this class is to provide thread-local variables, so there are many places to call this class thread-local variables.

Literally, this class creates a local variable for each thread. In fact, ThreadLocal creates a copy of the variable in each thread, so that each thread can access its own internal copy variable.

The problem of variable synchronization is usually considered when multithreading is mentioned, but ThreadLocal is not to solve the problem of variable synchronization shared by multithreads, but to make the variables of each thread not influence each other, which is equivalent to manipulating copies of variables between threads. Naturally, there is no need to consider the problem of multithreading competition, and there is no performance loss naturally.

Mode of use

Let's first take a look at these commonly used methods.

Public T get () {} public void set (T value) {} public void remove () {} protected T initialValue () {}

Obviously, the get () method gets the replica value owned by the thread, the set () method sets the value, the remove () method removes it, and initialValue () initializes the variable. Let's take a look at the following example and experience the application scenario.

Public class Demo {public static ThreadLocal threadLocal = null;public static void main (String [] args) {threadLocal = new ThreadLocal () {

/ * * initialize the value of ThreadLocal by overriding this method * / @ Overrideprotected Integer initialValue () {return 10;}}; MyThread T1 = new MyThread (20)

MyThread T2 = new MyThread (30); t1.start ()

/ / for a clear description, the try-catch statement block t1.join (); t2.start ();}} is omitted.

In the above method, we define and initialize a ThreadLock class of 10 (implemented by overriding the initialValue () method), and then start two threads, while we let the T2 thread wait for the T1 thread to finish execution

The details of the MyThread class are as follows

Class MyThread extends Thread {private int val = 0persMyThread (int val) {this.val = val;} @ Overridepublic void run () {System.out.println (Thread.currentThread () + "- BEFORE-" + Demo.threadLocal.get ()); Demo.threadLocal.set (val); System.out.println (Thread.currentThread () + "- AFTER-" + Demo.threadLocal.get ());}}

We get the current value by calling the get () method of the ThreadLocal object, then set a new value through the set () method (we set a different value for each thread), and then get the set value through the get () method

The running result is as follows

The key point is the initial value of the T2 thread variable marked in the figure. Although we have modified the value of the variable in the T1 thread, the value of the variable has not been changed in the T2 thread, thus realizing the unique variable of each thread.

At the same time, if a ThreadLocal object is to be reused in many places, you need to restore the local variable to its default value by calling the * * remove () * * method before using it.

Some people may ask, can't we define our own private variables for each thread to achieve the same operation? theoretically, of course, it is feasible, but ThreadLocal is far more convenient than the form of private variables, which can not only initialize uniformly outside the thread, but also avoid setting additional variables inside the thread.

Principle

Click into the source code of ThreadLocal and find that the field value of the variable is not stored. It seems that ThreadLocal is not responsible for saving the variable, so we can only start with the method.

Let's take a look at the initial () method. After all, the default initial value of our variable is set in this method, as follows

Protected T initialValue () {return null;}

We rewrite this method every time we create a ThreadLocal, so where exactly is this method called? we click into the source code of the get () method, as follows

Public T get () {

/ / get the current thread Thread t = Thread.currentThread ()

/ / get the mapThreadLocalMap map of the current thread = getMap (t)

If (map! = null) {ThreadLocalMap.Entry e = map.getEntry (this)

If (e! = null) {T result = (T) e.valuescape return result;}}

/ / create return setInitialValue () if map is empty;}

With a little eyebrow, we found that we got a ThreadLocalMap object here, so we thought it was possible to make a KV table between threads and variables to achieve that each thread has its own unique variable.

We click into the getMap (t) method and find that a threadLocals property of thread t is returned, which is a field of the Thread class:

ThreadLocal.ThreadLocalMap threadLocals = null

This is a property maintained by the ThreadLocal class, which is not modified by any of the methods of Thread, and the ThreadLocalMap itself is an inner class of ThreadLocal, which can be understood as a Map (although this class does not inherit the Map interface)

Also note that the Entry object (key-value pair) in the ThreadLocalMap object inherits a weak reference to ThreadLocaMap, as follows

Static class Entry extends WeakReference

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