Table of Contents
Usage
Implementation principle
Home Java javaTutorial What is the usage and principle of ThreadLocal in Java

What is the usage and principle of ThreadLocal in Java

Apr 13, 2023 pm 05:31 PM
java threadlocal

Usage

  • Isolate data between threads

  • Avoid passing parameters for every method in the thread, all methods in the thread You can directly obtain the objects managed in ThreadLocal.

package com.example.test1.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class AsyncTest {

    // 使用threadlocal管理
    private static final ThreadLocal<SimpleDateFormat> dateFormatLocal =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

    // 不用threadlocal进行管理,用于对比
    SimpleDateFormat dateFormat = new SimpleDateFormat();

    // 线程名称以task开头
    @Async("taskExecutor")
    public void formatDateSync(String format, Date date) throws InterruptedException {
        SimpleDateFormat simpleDateFormat = dateFormatLocal.get();
        simpleDateFormat.applyPattern(format);
        
        // 所有方法都可以直接使用这个变量,而不用根据形参传入
        doSomething();
        
        Thread.sleep(1000);
        System.out.println("sync " + Thread.currentThread().getName() +  " | " + simpleDateFormat.format(date));
        
        // 线程执行完毕,清除数据
        dateFormatLocal.remove();
    }

    // 线程名称以task2开头
    @Async("taskExecutor2")
    public void formatDate(String format, Date date) throws InterruptedException {
        dateFormat.applyPattern(format);
        Thread.sleep(1000);
        System.out.println("normal " + Thread.currentThread().getName() +  " | " + dateFormat.format(date));
    }
}
Copy after login

Use junit to test:

@Test
void test2() throws InterruptedException {
for(int index = 1; index <= 10; ++index){
String format = index + "-yyyy-MM-dd";
Date time = new Date();
asyncTest.formatDate(format, time);
}

for(int index = 1; index <= 10; ++index){
String format = index + "-yyyy-MM-dd";
Date time = new Date();
asyncTest.formatDateSync(format, time);
}
}
Copy after login

The results are as follows, you can see that variables that are not managed by ThreadLocal have been Unable to match the correct format.

sync task--10 | 10-2023-04-11
sync task--9 | 9-2023-04-11
normal task2-3 | 2-2023- 04-11
normal task2-5 | 2-2023-04-11
normal task2-10 | 2-2023-04-11
normal task2-6 | 2-2023-04-11
sync task--1 | 1-2023-04-11
normal task2-7 | 2-2023-04-11
normal task2-8 | 2-2023-04-11
normal task2- 9 | 2-2023-04-11
sync task--6 | 6-2023-04-11
sync task--3 | 3-2023-04-11
sync task--2 | 2-2023-04-11
sync task--7 | 7-2023-04-11
sync task--4 | 4-2023-04-11
sync task--8 | 8- 2023-04-11
normal task2-4 | 2-2023-04-11
normal task2-1 | 2-2023-04-11
sync task--5 | 5-2023-04- 11
normal task2-2 | 2-2023-04-11

Implementation principle

The process of obtaining data from ThreadLocal:

Get the corresponding thread first.

Get the ThreadLocalMap in the thread through getMap(t)

##ThreadLocalMap is a re-implemented hash table. Implements a hash based on two elements:

  • User-defined

    ThreadLocal object, for example: dateFormatLocal.

  • Entry object that encapsulates value.

Through the

map.getEntry(this) method, obtain the corresponding Entry# in the hash table based on the current threadlocal object ##If it is the first time to use

get()

, use setInitialValue() to call the user-overridden initialValue() method Create a map and initialize it with user-specified values. In this design, when the thread dies, the thread shared variable

ThreadLocalMap

will be destroyed. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings(&quot;unchecked&quot;) T result = (T)e.value; return result; } } return setInitialValue(); }</pre><div class="contentsignin">Copy after login</div></div> Note

Entry

The object is a weak reference: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>static class Entry extends WeakReference&lt;ThreadLocal&lt;?&gt;&gt; { /** The value associated with this ThreadLocal. */ Object value; // k: ThreadLocal, v: value Entry(ThreadLocal&lt;?&gt; k, Object v) { super(k); value = v; } }</pre><div class="contentsignin">Copy after login</div></div> The common usage of weak reference is:

WeakReference<RoleDTO> weakReference = new WeakReference<>(new RoleDTO());
Copy after login

Therefore, in

Entry

, k represents the ThreadLocal object, which is a weak reference. v represents the value managed by ThreadLocal, which is a strong reference. Memory Leak

Memory Leak

means that useless objects (objects no longer used) continue to occupy memory or the memory of useless objects cannot be released in time, resulting in memory leakage. The waste of space is called a memory leak. As the garbage collector activity increases and memory usage continues to increase, program performance will gradually decline. In extreme cases, OutOfMemoryError will be triggered, causing the program to crash. Memory leak problems mainly occur in the thread pool, because the threads in the thread pool are continuously executed and new tasks are continuously obtained from the task queue for execution. However, there may be

ThreadLocal

objects in the task, and the ThreadLocal of these objects will be saved in the thread's ThreadLocalMap, so ThreadLocalMap will become more and more big. But

ThreadLocal

is passed in by the task (worker). After a task is executed, the corresponding ThreadLocal object will be destroyed. The relationship in the thread is: Thread -> ThreadLoalMap -> Entry<ThreadLocal, Object>. ThreadLocalBecause it is a weak reference, it will be destroyed during GC, which will cause Entry<null, Object> to exist in ThreadLoalMap.

Use remove()

Since the threads in the thread pool are always running, if

ThreadLoalMap

is not cleaned up, then Entry< null, Object> will always occupy memory. The remove() method will clear the Entry of key==null.

Use static modification

Set

ThreadLocal

to static to avoid passing a thread class into the thread pool multiple times Repeat to create Entry. For example, there is a user-defined thread <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>public class Test implements Runnable{ private static ThreadLocal&lt;Integer&gt; local = new ThreadLocal&lt;&gt;(); @Override public void run() { // do something } }</pre><div class="contentsignin">Copy after login</div></div> that uses the thread pool to handle 10 tasks. Then a

Entry

will be saved in the Thread.ThreadLocalMap of each thread used to process tasks in the thread pool, due to the addition of the static key Word, all local variables in Entry in each thread refer to the same variable. Even if a memory leak occurs at this time, all Test classes will have only one local object, which will not cause excessive memory usage.

@Test
void contextLoads() {
   Runnable runnable = () -> {
      System.out.println(Thread.currentThread().getName());
   };

   for(int index = 1; index <= 10; ++index){
      taskExecutor2.submit(new com.example.test1.service.Test());
   }
}
Copy after login

The above is the detailed content of What is the usage and principle of ThreadLocal in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

See all articles