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

What is the usage and principle of ThreadLocal in Java

王林
王林forward
2023-04-13 17:31:121030browse

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));
    }
}

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);
}
}

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. <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> Note

Entry

The object is a weak reference: <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> The common usage of weak reference is:

WeakReference<RoleDTO> weakReference = new WeakReference<>(new RoleDTO());

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 -> Entry8cea09e86e6da166e71a296f2b1f24bd. ThreadLocalBecause it is a weak reference, it will be destroyed during GC, which will cause Entry5e33282b25ec20a016ad69d03248472f to exist in ThreadLoalMap.

Use remove()

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

ThreadLoalMap

is not cleaned up, then Entry2ce275f7b95bd469e229891ac13142eb 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 <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> that uses the thread pool to handle 10 tasks. Then a

Entry70cecb753554e47d1300fe45bef564fc

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. <pre class="brush:java;">@Test void contextLoads() { Runnable runnable = () -&gt; { System.out.println(Thread.currentThread().getName()); }; for(int index = 1; index &lt;= 10; ++index){ taskExecutor2.submit(new com.example.test1.service.Test()); } }</pre>

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:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete