设为首页 加入收藏

TOP

Java中ThreadLocal的用法和原理(一)
2023-07-25 21:32:20 】 浏览:42
Tags:Java ThreadLocal

用法

  • 隔离各个线程间的数据
  • 避免线程内每个方法都进行传参,线程内的所有方法都可以直接获取到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));
    }
}

使用junit进行测试:

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

结果如下,可以看到没有被 ThreadLocal 管理的变量已经无法匹配正确的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

实现原理

ThreadLocal中获取数据的过程:

  • 先获取对应的线程。
  • 通过 getMap(t)拿到线程中的 ThreadLocalMap
  • ThreadLocalMap 是一个重新实现的散列表,基于两个元素实现散列:
    • 用户定义的ThreadLocal对象,例如:dateFormatLocal
    • 封装了valueEntry对象。
  • 通过map.getEntry(this)方法,根据当前的 threadlocal对象在散列表中获得对应的Entry
  • 如果是第一次使用get(), 则使用 setInitialValue()调用用户重写的initialValue()方法创建map并使用用户指定的值初始化。

在这种设计方式下,线程死去的时候,线程共享变量ThreadLocalMap会被销毁。

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

注意 Entry对象是弱引用:

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

    // k: ThreadLocal, v: value
    Entry(ThreadLocal<?> k, Ob
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Spring源码系列:初探底层,手写S.. 下一篇JdkProxy的进阶知识

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目