首页 技术 正文
技术 2022年11月19日
0 收藏 946 点赞 2,356 浏览 1155 个字

ThreadLocal类可以看作是当前线程的一个局部变量,只有当前线程可以访问,因此是线程安全的。

ThreadLocal内部维护了一个ThreadLocalMap类,ThreadLocalMap是一个定制的hash map,用于维护ThreadLocal类的value。

首先来看set方法的实现:

public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}

可以看到,set方法时将当前线程对象Thread作为key设置到ThreadLocalMap中去。

首先通过当前线程对象获取到threadLocalMap对象,如果获取到,则更新值,获取失败,则创建并更新值。

我们看看createMap的实现:

void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}

ThreadLocalMap对象内部维护了一个弱引用的Entry对象,Entry对象使用当前的ThreadLocal对象作为key。

再来看看get方法:

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

还是通过当前线程对象获取到map,然后取出存放在map中的值。

最后,ThreadLocal对象的生命周期是线程的生命周期,它会先线程退出的时候 被销毁,如果希望及时回收设置进ThreadLocal中的对象,可以手动调用ThreadLocal.remove()方法。防止内存泄漏。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919