search
HomeJavajavaTutorialA brief analysis of ThreadLocal principle
A brief analysis of ThreadLocal principleSep 29, 2019 pm 04:18 PM
javathreadlocal

ThreadLocal means thread local variables! So what are thread local variables? What's the use of this thing? Is it that you were asked in an interview and you couldn’t tell me anything? Today, let’s take a look at the source code of this product and fundamentally understand what it does.

A brief analysis of ThreadLocal principle

The relationship between Thread, ThreadLocalMap, and Entry

In fact, after studying his source code implementation, it is actually not as complicated as imagined , the main points are as follows:

1. Java can obtain the current Thread instance object through Thread.currentThread(). Now that we can get the Thread object instance, we can operate the instance (properties), such as setting a value for the Thread object.

2. Each Thread object has a ThradLocalMap instance, which has an array of Entries. The Entry object has two main attributes: value and weak reference to ThreadLocal, where the value attribute is the value setting. It is held by the current thread and is also the core attribute of ThreadLocal:

static class Entry extends WeakReference<ThreadLocal<?>> {
    /** The value associated with this ThreadLocal. */
    Object value;

    Entry(ThreadLocal<?> k, Object v) {
        super(k);
        value = v;
    }
}

Note that Entry inherits from WeakReference, and its key is the ThreadLocal object! (Figure 1)

A brief analysis of ThreadLocal principle

Combining the two knowledge points 1 and 2, we can know that after we get the Thread object, we can control the ThreadLocalMap object of the current thread object, and then Give the value you want to save to the value attribute of ThreadLocalMap's Entry. The relationship between Thread, ThreadLocalMap, and value can be represented by the following figure (Figure 2):

A brief analysis of ThreadLocal principle

We can draw this conclusion from the above picture: a Thread object holds a ThreadLocalMap object, and then a ThreadLoalMap object contains multiple ThreadLlocal objects and the value of the thread where the ThreadLocal object is located! ! ! In a nutshell: A Thread object can hold the variable values ​​​​of multiple ThreadLocal objects

So what is the relationship between ThreadLocal and Thread? How can the two read the value? Below is a brief analysis based on the source code.

The relationship between ThreadLocal and Thread

First look at the set method of ThreadLocal:

 public void set(T value) {
         //获取当前线程
        Thread t = Thread.currentThread();
        //获取当前线程持有的ThreadLocalMap
        ThreadLocal.ThreadLocalMap map = getMap(t);
        //将value设置给threadlocalMap
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

The set method is very logical and simple (j combined with Figure 2 above See for better understanding):

1. Get the current Thread object through the currentThread method

2. Get the ThreadLoalMap object of the current Thread object

3. Add value together with the ThreadLocal object Form an Entry object yourself and save it in the Entry type array of

ThreadLoalMap.

Let’s take a look at the get method of ThreadLocal:

public T get() {
    //获取当前线程
    Thread t = Thread.currentThread();
    //获取当前线程的ThreadLocalMap对象
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        //获取与ThreadLocal对象想关联的value
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            //获取值
            T result = (T)e.value;
            return result;
        }
    }
    //为空返回初始化值
    return setInitialValue();
}

The overall logic of get can be developed and it is also very simple:

1. Get Current Thread object

2. Get the ThreadLocalMap object of the current Thread object

3. Get the Entry object associated with ThreadLocal from ThreadLocalMap, specifically using ThreadLocal as the key.

4. Get the value attribute of the Entry in step 3 and return it.

By observing the get and set methods as a whole, we can draw the following conclusions: calling the set method of the ThreadLocal object is to add value to the ThreadLocalMap of the Thread object; calling the get method of the ThreadLocal object is to obtain the value from the ThreadLocalMap of the Thread object. The core is to manipulate the ThreadLocalMap object of the Thread object to read and write value. The principle is that simple.

So what is the relationship between different ThreadLocal objects located in different threads and saving values ​​in other threads? It can be clearly described through the following picture:

A brief analysis of ThreadLocal principle

Example of ThreadLocal usage

We know that in Android there are only A Looper object, so how is it done? It is ThreadLocal that plays a role. Take a look at Looper's prepare method:

//定义一个静态的ThreadLocal变量
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); 

private static void prepare(boolean quitAllowed) {
        //一个Thread只能关联一个Looper对象
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper(quitAllowed));
    }

You can know by observing the prepare method. First, use the get method of sThreadLocal to determine whether the current thread already owns a Looper object. If so, throw an exception. ; If the current thread has not set a Looper object, call the set method of ThreadLocal to initialize a Looper object and hand it to the current thread:

sThreadLocal.set(new Looper(quitAllowed));

This ensures that a thread has only one Looper object.

So far, the principle of ThreadLocal has been basically analyzed. As for how to set and get internally, the blogger has not done too detailed analysis because it is not necessary to understand the working reasons and usage scenarios of ThreadLocal. That’s it.

The above is the detailed content of A brief analysis of ThreadLocal principle. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Java ThreadLocal类如何使用Java ThreadLocal类如何使用May 14, 2023 pm 06:49 PM

如图所示:快速开始接下来我们就先用一个简单的样例给大家展示一下ThreadLocal的基本用法packagecuit.pymjl.thradlocal;/***@authorPymjl*@version1.0*@date2022/7/110:56**/publicclassMainTest{staticThreadLocalthreadLocal=newThreadLocal();staticvoidprint(Stringstr){//打印当前线程中本地内存中本地变量的值System.out.

Java自定义过滤器和拦截器实现ThreadLocal线程封闭Java自定义过滤器和拦截器实现ThreadLocal线程封闭May 15, 2023 pm 11:40 PM

线程封闭线程封闭一般通过以下三个方法:Ad-hoc线程封闭:程序控制实现,最糟糕,忽略堆栈封闭:局部变量,无并发问题ThreadLocal线程封闭:特别好的封闭方法方法2是最常用的,变量定义在接口内,本文主要讲解方法三,SpringBoot项目通过自定义过滤器和拦截器实现ThreadLocal线程封闭。实现Filter接口自定义过滤器和继承HandlerInterceptorAdapter自定义拦截器。ThreadLocal线程封闭实现步骤封装ThredLocal的方法/***自定义Reques

带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

SpringBoot通过ThreadLocal怎么实现登录拦截SpringBoot通过ThreadLocal怎么实现登录拦截May 22, 2023 pm 12:04 PM

1前言注册登录可以说是平时开发中最常见的东西了,但是一般进入到公司之后,像这样的功能早就开发完了,除非是新的项目。这两天就碰巧遇到了这样一个需求,完成pc端的注册登录功能。实现这样的需求有很多种方式:像1)HandlerInterceptor+WebMvcConfigurer+ThreadLocal2)Filter过滤器3)安全框架Shiro(轻量级框架)4)安全框架SpringSecurety(重量级框架)而我采用的是第一种SpringHandlerInterceptor+WebMvcConf

Java利用ThreadLocal类的get()函数获取线程局部变量的值Java利用ThreadLocal类的get()函数获取线程局部变量的值Jul 24, 2023 pm 02:40 PM

Java利用ThreadLocal类的get()函数获取线程局部变量的值在并发编程中,多个线程可能会访问同一个变量,这时需要考虑线程安全的问题。为了解决这个问题,Java提供了ThreadLocal类,它可以实现线程间的数据隔离,从而保证每个线程都有自己的变量副本。在ThreadLocal类中,我们可以使用get()函数来获取当前线程的局部变量值。在使用Th

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools