关于 ThreadLocal,我们经常用它来解决多线程并发问题,那它究竟是如何做到的?今天就让我们来好好看一下。

从源码入手

首先,让我们看看 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 instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

按照文中所述,ThreadLocal 提供的是线程本地变量,每个线程都有一份单独的副本,经常使用的方式是私有静态变量。关键在于下一段,线程存活,ThreadLocal 实例就可以被访问,线程消失,就会被垃圾回收。

get()方法

看到这儿,有没有想起上一篇内容所说的引用类型,有可能是软引用或者弱引用,具体是什么呢?还是来看看代码:

    public T get() {
// 获取当前线程
Thread t = Thread.currentThread();
// 获取线程里的map
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();
} ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}

上面展示的是 ThreadLocal 中的get()方法,关键的 map 是在 Thread 类中的threadLocals变量,让我们继续看看 ThreadLocalMap 的源代码:

    ThreadLocal.ThreadLocalMap threadLocals = null;

    static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value; Entry(ThreadLocal<?> k, Object v) {
// 使用ThreadLocal作为key,并且是弱引用
super(k);
value = v;
}
} // 省略代码
}

根据上一篇文章所述,如果一个对象只有弱引用,那么当下一次 GC 进行时,该对象就会被回收。那么让我们整理一下:

  1. ThreadLocalMap 的 Entry 对 ThreadLocal 的引用为弱引用
  2. ThreadLocal 本身并不存储值,具体的 value 依旧在各个线程中。因此你可以把 ThreadLocal 看成一个工具类。

但需要注意的是,Entry 中,只有key是弱引用,但 value 依旧是强引用。那会不会出现 key 被垃圾回收后,这个 map 的 key 为 null,但 value 依旧存在的情况呢?

set()方法

确实是有可能的,但 JDK 本身也做了优化,可以看看 ThreadLocalMap 的 set()方法:

        private void set(ThreadLocal<?> key, Object value) {

            // We don't use a fast path as with get() because it is at
// least as common to use set() to create new entries as
// it is to replace existing ones, in which case, a fast
// path would fail more often than not. Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1); for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get(); if (k == key) {
e.value = value;
return;
} if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
} tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}

调用 set()的时候,ThreadLocalMap 检查到 key 为 null 的 entry 时,会将 value 也设置为 null,这样 value 之前对应的实例也可以被回收。

使用场景

简单使用

先让我们看一个简单的例子:

public class ThreadLocalSimpleDemo {

    public static void main(String[] args) {
int threads = 3;
InnerClass innerClass = new InnerClass();
for (int i = 1; i <= threads; i++) {
new Thread(() -> {
for (int j = 0; j < 4; j++) {
innerClass.add(String.valueOf(j));
innerClass.print();
}
innerClass.set("hello world");
}, "thread - " + i).start();
}
} private static class InnerClass { /**
* 添加
*/
public void add(String newStr) {
StringBuilder str = Counter.counter.get();
Counter.counter.set(str.append(newStr));
} /**
* 打印
*/
public void print() {
System.out.printf(
"Thread name:%s , ThreadLocal hashcode:%s, Instance hashcode:%s, Value:%s\n",
Thread.currentThread().getName(),
Counter.counter.hashCode(),
Counter.counter.get().hashCode(),
Counter.counter.get().toString()
);
} /**
* 赋值
*/
public void set(String words) {
Counter.counter.set(new StringBuilder(words));
System.out.printf(
"Set, Thread name:%s , ThreadLocal hashcode:%s, Instance hashcode:%s, Value:%s\n",
Thread.currentThread().getName(),
Counter.counter.hashCode(),
Counter.counter.get().hashCode(),
Counter.counter.get().toString()
);
}
} private static class Counter {
/**
* 初始化时是一个空的StringBuilder对象
*/
private static ThreadLocal<StringBuilder> counter = ThreadLocal.withInitial(StringBuilder::new);
}
}

其打印结果为:

Thread name:thread - 3 , ThreadLocal hashcode:310471657, Instance hashcode:640658548, Value:0
Thread name:thread - 2 , ThreadLocal hashcode:310471657, Instance hashcode:126253473, Value:0
Thread name:thread - 2 , ThreadLocal hashcode:310471657, Instance hashcode:126253473, Value:01
Thread name:thread - 2 , ThreadLocal hashcode:310471657, Instance hashcode:126253473, Value:012
Thread name:thread - 2 , ThreadLocal hashcode:310471657, Instance hashcode:126253473, Value:0123
Thread name:thread - 1 , ThreadLocal hashcode:310471657, Instance hashcode:829132711, Value:0
Thread name:thread - 1 , ThreadLocal hashcode:310471657, Instance hashcode:829132711, Value:01
Thread name:thread - 1 , ThreadLocal hashcode:310471657, Instance hashcode:829132711, Value:012
Thread name:thread - 1 , ThreadLocal hashcode:310471657, Instance hashcode:829132711, Value:0123
Set, Thread name:thread - 1 , ThreadLocal hashcode:310471657, Instance hashcode:820066274, Value:hello world
Thread name:thread - 3 , ThreadLocal hashcode:310471657, Instance hashcode:640658548, Value:01
Thread name:thread - 3 , ThreadLocal hashcode:310471657, Instance hashcode:640658548, Value:012
Set, Thread name:thread - 2 , ThreadLocal hashcode:310471657, Instance hashcode:155293473, Value:hello world
Thread name:thread - 3 , ThreadLocal hashcode:310471657, Instance hashcode:640658548, Value:0123
Set, Thread name:thread - 3 , ThreadLocal hashcode:310471657, Instance hashcode:1804272849, Value:hello world

可以看出,我们在使用 ThreadLocal 时,用的是同一个对象,但各个线程对应的实例是不一样的。而在调用 set() 方法后,对应的实例会被替换。

Session

对于 Java Web 应用而言,Session 保存了很多信息。很多时候需要通过 Session 获取信息,有些时候又需要修改 Session 的信息。一方面,需要保证每个线程有自己单独的 Session 实例。另一方面,由于很多地方都需要操作 Session,存在多方法共享 Session 的需求。使用 ThreadLocal 进行实现:

public class SessionHandler {

  public static ThreadLocal<Session> session = ThreadLocal.<Session>withInitial(() -> new Session());

  @Data
public static class Session {
private String id;
private String user;
private String status;
} public String getUser() {
return session.get().getUser();
} public String getStatus() {
return session.get().getStatus();
} public void setStatus(String status) {
session.get().setStatus(status);
} public static void main(String[] args) {
new Thread(() -> {
SessionHandler handler = new SessionHandler();
handler.getStatus();
handler.getUser();
handler.setStatus("close");
handler.getStatus();
}).start();
}
}

总结

ThreadLocal 使用起来虽然简单,但考虑到其设计确实很精巧,值得了解一下。

有兴趣的话可以访问我的博客或者关注我的公众号、头条号,说不定会有意外的惊喜。

https://death00.github.io/

Java中的ThreadLocal的更多相关文章

  1. Java中的ThreadLocal深入理解

    提到ThreadLocal,有些Android或者Java程序员可能有所陌生,可能会提出种种问题,它是做什么的,是不是和线程有关,怎么使用呢?等等问题,本文将总结一下我对ThreadLocal的理解和 ...

  2. 理解Java中的ThreadLocal

    提到ThreadLocal,有些Android或者Java程序员可能有所陌生,可能会提出种种问题,它是做什么的,是不是和线程有关,怎么使用呢?等等问题,本文将总结一下我对ThreadLocal的理解和 ...

  3. Java中的ThreadLocal详解

    一.ThreadLocal简介 多线程访问同一个共享变量的时候容易出现并发问题,特别是多个线程对一个变量进行写入的时候,为了保证线程安全,一般使用者在访问共享变量的时候需要进行额外的同步措施才能保证线 ...

  4. 谈谈Java中的ThreadLocal

    什么是ThreadLocal ThreadLocal一般称为线程本地变量,它是一种特殊的线程绑定机制,将变量与线程绑定在一起,为每一个线程维护一个独立的变量副本.通过ThreadLocal可以将对象的 ...

  5. 理解java中的ThreadLocal(转)

    一.对ThreadLocal概述 JDK API 写道: 该类提供了线程局部 (thread-local) 变量.这些变量不同于它们的普通对应物,因为访问某个变量(通过其 get 或 set 方法)的 ...

  6. 理解java中的ThreadLocal 专题

    ThreadLocal每一印象: public class IncrementWithStaticVariable{ private static int seqNum = 0; public int ...

  7. java 中的 ThreadLocal

    首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的.各 ...

  8. Java中的ThreadLocal使用

    ThreadLocal用于下面的场景: 1. 不允许多个线程同时访问的资源 2. 单个线程存活过程只使用一个实例 官方定义如下: This class provides thread-local va ...

  9. Java ThreadLocal Example(java中的ThreadLocal例子)

    Java ThreadLocal is used to create thread local variables. We know that all threads of an Object sha ...

随机推荐

  1. 【使用篇二】Lombok的介绍与使用(16)

    Lombok通过简单注解来实现精简代码来达到消除冗长代码的目的.它能够提高编码效率.使代码更简洁.消除冗长代码.避免修改字段名时忘记修改方法名. 一.Lombok注解 Lombok主要常用的注解有: ...

  2. DEBUG的基本命令的使用[MASM]

    DEBUG的基本命令的使用 DEBUG是专门为汇编语言设计的一种调试工具,它通过步进,设置断点等方式为汇编语言程序员提供了非常有效的调试手段. DEBUG的命令都是一个字母,后跟一个或多个参数:字母  ...

  3. centos7安装服务器之安装禅道

    Centos7下安装禅道 1. 下载禅道的linux版本 我的centos7的版本为:7.7版本 2. 将下载的包上传到centos7服务器上 3. 将禅道压缩包解压到/opt目录下: 4. 启动禅道 ...

  4. Redis入门(三)-Redis的安装及操作key的命令介绍

    前两节对Redis做了一些详细的介绍,那么接下来开始我们就正式进入Redis的学习阶段. 安装Redis Windows下安装redis非常方便, 下载压缩包解压即可使用. 链接:https://pa ...

  5. 织女星开发板RISC-V内核实现微秒级精确延时

    前言 收到VEGA织女星开发板也有一段时间了,好久没玩了,想驱动个OLED屏,但是首先要实现IIC协议,而实现IIC协议,最基本的就是需要一个精确的延时函数,所以研究了一下如何来写一个精确的延时函数. ...

  6. Python 从入门到进阶之路(三)

    在之前的文章我们介绍了一下 Python 中 if while for 的使用,本章我们来看一下 Python 中的变量类型. 在 Python 定义变量时的规则是 变量名 = 变量 ,Python ...

  7. RabbitMQ的高级特性概念理解

    1.RabbitMQ中的消息如何保障百分之百的投递成功? 答:百分之百的投递成功,方案可以参考下面的2.3. 2.什么是生产者端的可靠性投递? 答:第一步,生产者保障消息的成功发出.第二步,保障Rab ...

  8. Python进阶一

    文章目录 异常处理 1 基本用法 2高级用法 逻辑运算符 循环的高级用法 异常处理1 基本用法应对所有情况 try: 1/0 except: print('某原因异常') 应对特定异常情况 try: ...

  9. echarts 柱状图+折线+文字倾斜及省略

    效果图: 代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  10. [转]RPA认证 Developer UIPath Certificate,细说uipath认证学习,Online Quiz和Practical Exam项目详解

    本文转自:https://blog.csdn.net/u010369735/article/details/88621195 UIPath,RPA里算是比较简单易操作的一款软件了,因为公司业务的需要, ...