Home > Java > javaTutorial > What is the usage and principle of ThreadLocal in Java

What is the usage and principle of ThreadLocal in Java

王林
Release: 2023-04-13 17:31:12
forward
1095 people have browsed it

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:java;">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:java;">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:java;">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!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template