用法隔离各个线程间的数据
避免线程内每个方法都进行传参,线程内的所有方法都可以直接获取到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;@componentpublic 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进行测试:
@testvoid 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。
封装了value的entry对象。
通过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, object v) { super(k); value = v; }}
弱引用的常见用法是:
weakreference<roledto> weakreference = new weakreference<>(new roledto());
因此,在entry中,k 代表threadlocal对象,它是弱引用。v代表threadlocal管理的那个value,是强引用。
内存泄漏内存泄漏是指无用对象(不再使用的对象)持续占有内存或无用对象的内存得不到及时释放,从而造成内存空间的浪费称为内存泄漏。随着垃圾回收器活动的增加以及内存占用的不断增加,程序性能会逐渐表现出来下降,极端情况下,会引发outofmemoryerror导致程序崩溃。
内存泄漏问题主要在线程池中出现,因为线程池中的线程是不断执行的,从任务队列中不断获取新的任务执行。但是任务中可能有threadlocal对象,这些对象的threadlocal会保存在线程的threadlocalmap中,因此threadlocalmap会越来越大。
但是threadlocal是由任务(worker)传入的,一个任务执行结束后,对应的threadlocal对象会被销毁。线程中的关系是: thread -> threadloalmap -> entry<threadlocal, object>。threadlocal由于是弱引用会,在gc的时候会被销毁,这会导致 threadloalmap中存在entry<null, object>。
使用remove()
由于线程池中的线程一直在运行,如果不对threadloalmap进行清理,那entry<null, object>会一直占用内存。remove()方法会清除key==null的entry。
使用static修饰
将threadlocal设置成static可以避免一个线程类多次传入线程池后重复创建entry。例如,有一个用户定义的线程
public class test implements runnable{ private static threadlocal<integer> local = new threadlocal<>(); @override public void run() { // do something }}
使用线程池处理10个任务。那么线程池中每个用来处理任务的线程的thread.threadlocalmap中都会保存一个entry<local, integer>,由于添加了static关键字,所有每个线程中的entry中的local变量引用的都是同一个变量。这时就算发生内存泄漏,所有的test类也只有一个local对象,不会导致内存占用过多。
@testvoid contextloads() { runnable runnable = () -> { system.out.println(thread.currentthread().getname()); }; for(int index = 1; index <= 10; ++index){ taskexecutor2.submit(new com.example.test1.service.test()); }}
以上就是java中threadlocal的用法和原理是什么的详细内容。