ThreadLocal 简述
ThreadLocal的理解
Java中的ThreadLocal类允许我们创建只能被同一个线程读写的变量。因此,如果一段代码含有一个ThreadLocal变量的引用,即使两个线程同时执行这段代码,它们也无法访问到对方的ThreadLocal变量。
The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.
解析ThreadLocal类
- ThreadLocal中 get()方法的实现
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
判断当前线程,通过getMap 方法返回一个ThreadLocalMap 。
判断map 是否为null ,如果存在的话,就从ThreadLocalMap中获取对应的value,不存在调用setInitialValue方法。
来看看getMap方法的实现。
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
getMap传入当前的线程返回一个threadLocals,成员变量threadLocals是什么?
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
再来看看 ThreadLocalMap ,通过map来实现key-value 的存储。
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal k, Object v) {
super(k);
value = v;
}
}
/**
* Set the value associated with key.
*
* @param key the thread local object
* @param value the value to be 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();
}
- ThreadLocal中set()方法的实现
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
拷贝一个当前的线程,和上面的get方法对应起来看。这里也是get来进行判断。
代码测试
public class ThreadLocalTest implements Runnable {
private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
@Override
public void run() {
threadLocal.set((int) (Math.random() * 100D));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println(threadLocal.get());
}
public static void main(String[] args) throws Exception {
ThreadLocalTest sharedRunnableInstance = new ThreadLocalTest();
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);
thread1.start();
thread2.start();
thread1.join(); // wait for thread 1 to terminate
thread2.join(); // wait for thread 2 to terminate
}
}
总结
上面的例子,将ThreadLocalTest 实例传递給两个线程,执行run 方法这两个线程分别保存了不同的数据。如果不是访问ThreadLocal对象,第2个线程会覆盖掉第1个线程的值。ThreadLocal不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的。各个线程中访问的是不同的对象。
ThreadLocal使用场景,多线程实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。 ThreadLocal 也常用数据库连接操作。
参考
ThreadLocal 简述的更多相关文章
- java并发:线程同步机制之ThreadLocal
1.简述ThreadLocal ThreadLocal实例通常作为静态的私有的(private static)字段出现在一个类中,这个类用来关联一个线程.ThreadLocal是一个线程级别的局部变量 ...
- ThreadLocal父子线程传递实现方案
介绍InheritableThreadLocal之前,假设对 ThreadLocal 已经有了一定的理解,比如基本概念,原理,如果没有,可以参考:ThreadLocal源码分析解密.在讲解之前我们先列 ...
- java引用类型简述
主要内容: 1.引用类型简述 2.对象的可达性 3.软引用的垃圾回收分析 4.WeakHashMap分析 5.ThreadLocal内存泄漏分析 1.引用类型简述 在Java语言中除了基本数据类型外, ...
- 【原理】Java的ThreadLocal实现原理浅读
当前线程的值传递,ThreadLocal 通过ThreadLocal设值,在线程内可获取,即时获取值时在其它Class或其它Method. public class BasicUsage { priv ...
- JVM参数简述
java虚拟机启动时会带有很多的启动参数,Java命令本身就是一个多参数的启动命令.那么具体JVM启动包含哪些参数呢?这篇文章针对java8的情况做一篇汇总解读,包含大多数常见和不常见的命令参数,过于 ...
- Netty源码分析第5章(ByteBuf)---->第4节: PooledByteBufAllocator简述
Netty源码分析第五章: ByteBuf 第四节: PooledByteBufAllocator简述 上一小节简单介绍了ByteBufAllocator以及其子类UnPooledByteBufAll ...
- ThreadLocal 从源码角度简单分析
目录 ThreadLcoal源码浅析 ThreadLocal的垃圾回收 Java引用 ThreadLocal的回收 各线程中threadLocalMap的回收 内存泄露问题 总结 参考 ThreadL ...
- Java线程之ThreadLocal
翻译:https://www.journaldev.com/1076/java-threadlocal-example?utm_source=website&utm_medium=sideba ...
- ThreadLocal是什么?使用场景有哪些?
什么是ThreadLocal? ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本. 测试代码: package ...
随机推荐
- GBK,UTF8是什么?有什么区别,做网站选择哪种好?
GBK包含全部中文字符: UTF-8则包含全世界所有国家需要用到的字符. GBK是在国家标准GB2312基础上扩容后兼容GB2312的标准(好像还不是国家标准) UTF-8编码的文字可以在各国各种支持 ...
- Win7如何解决telnet不是内部或外部命令的方案!听语音
Telnet用于远程操作互联网中的设备或终端计算机服务器,可以有效的减少现场操作的麻烦.因为设备或终端是遍布整个省或市,有的甚至是国外,如何高效的处理问题是当务之急,除了telnet还可以ssh使用c ...
- 常用排序算法java实现
写在前面:纸上得来终觉浅.基本排序算法的思想,可能很多人都说的头头是到,但能说和能写出来,真的还是有很大区别的. 今天整理了一下各种常用排序算法,当然还不全,后面会继续补充.代码中可能有累赘或错误的地 ...
- JAVA WEB之Spring4.x JdbcTemplate
jdbcTemplate 说白了,他就是Spring提供用于简化数据库访问的类 基本jdbc驱动访问数据库 /* 一个简易好用的数据库连接和访问类 */ package cslg.cn.control ...
- JavaScript学习日志:关于js分号
javascript有自动添加分号的功能,但是不是所有情况都会自动添加,要区分: 1,如果语句独占一行 如果当前行内的语句能够被js正确解析,那么就会在句尾添加一个分号. (如何判断是否正确解析?你在 ...
- 单词拼写检查之cutoff距离
前言 cutoff是一个比较冷门的概念,相比于DP经典算法的编辑距离,cutoff距离只局限于自然语言处理领域.提出cutoff距离的起因很简单,因为经典的编辑距离无法很好地衡量在字符串搜索过程中的编 ...
- 未找到约束ContractName Microsoft.VisualStudio.Text.ITextDocumentFactoryServiceRequiredTypeIdentity匹配的导出的解决办法
未找到约束ContractName Microsoft.VisualStudio.Text.ITextDocumentFactoryServiceRequiredTypeIdentity Micros ...
- Azure Powershell获取指定订阅下的虚拟机信息(ASM)
为方便Azure用户导出已创建虚拟机的相关信息,特编写如下脚本: 详情脚本: # 登陆Azure Account Add-AzureAccount -Environment AzureChinaClo ...
- Servlet开篇
Servlet开篇 前面我已经说过好多遍了,如何学习好一个东西其实就是2个问题: 1,这个东西是干嘛的?为什么要玩这个东西? 2,怎么样就玩好这个东西了?具体的应该玩这个东西的什么? 其实现在对于我来 ...
- trait
参考 引文 在php中,为实现代码复用,有了继承,但是一个类只能继承一个父类,不支持多继承,接口支持多实现,但是接口又不太一样,接口对外负责功能调用声明,不负责实现,由实现了接口的类去实现具体功能逻辑 ...