- ThreadLocal的作用,解决的问题
- 用法
- 实现机制
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one via its get or set method has its own, independently initialized copy of the variable.
ThreadLocal是Thread Local Variable(线程局部变量)的意思,ThreadLocal为每个使用该变量的线程分配一个独立的变量副本,每个线程可以独立的修改自己的副本,好像每个线程完全拥有该变量一样
用法
void set(Object value)
设置当前线程的线程局部变量的值
public Object get()
返回当前线程对应的线程局部变量
public void remove()
将当前线程局部变量的值删除
protected Object initialValue()
返回该线程局部变量的初始值,默认实现的是返回null,子类可以覆盖。
实现机制
ThreadLocal类中有一个ThreadLocalMap,用于存储每个线程的变量副本,Map中,键为线程对象,值为线程的变量副本。
使用场景
spring里面很多地方都用到了,看看Sping3.0企业级开发相关章节
比如以下的性能监控
import java.util.concurrent.TimeUnit;
public class ThreadLocalTest1 {
private static final ThreadLocal<Long>TIME_THREADLOCAL = new ThreadLocal<Long>(){
protected Long initialValue(){
return System.currentTimeMillis();
}
};
public static final void begin(){
TIME_THREADLOCAL.set(System.currentTimeMillis());
}
public static final long end(){
return System.currentTimeMillis() - TIME_THREADLOCAL.get();
}
public static void main(String[] args) throws Exception {
ThreadLocalTest1.begin();
TimeUnit.SECONDS.sleep(1);
System.out.println("Cost: " + ThreadLocalTest1.end() + " mills");
}
}
在Thread类里,有ThreadLocal类的内部类ThreadLocalMap对象的引用
/* ThreadLocal values pertaining to this thread. This map
* is maintained by the ThreadLocal class.
*/
ThreadLocal.ThreadLocalMap threadLocals = null;
/*
* InheritableThreadLocal values pertaining to this
* thread. This map is
* maintained by the InheritableThreadLocal class.
*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
想弄明白的有空看看源码吧,有空再写,发现别人写的还是比自己总结得好很多,贴点链接也是不错的吧
ThreadLocal 那点事儿
聊一聊ThreadLocal
深入浅出ThreadLocal
ThreadLocal可能会引起内存泄露吗
帮助理解,图片来源于最后一个链接: