ThreadLocal是在是Thread的一个局部变量,今天我来分析了一下这个类

先看ThreadLocal的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);
}

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

在去Thread类中找threadLocals的定义

    /* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;

此时调用

ThreadLocal的set方法时。map对象肯定是个null,那么就会createMap,如今再去看一下createMap方法

    /**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
* @param map the map to store.
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}

如今再去看一下ThreadLocalMap的构造方法

        /**
* Construct a new map initially containing (firstKey, firstValue).
* ThreadLocalMaps are constructed lazily, so we only create
* one when we have at least one entry to put in it.
*/
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);
}

从这儿看到。事实上就是声明了一个Entry的数组,然后将我们传入的key和value组成一个Entry对象,然后存到Entry数组里面

如今再去看一下,Entry类又是啥

        /**
* 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;
}
}

这里面继承WeakReference的意思是说,这是一个弱类型,就是告诉垃圾回收器指向的对象是可能被回收的。

WeakReference就是继承的Reference类

public class WeakReference<T> extends Reference<T> 

终于是调的Reference的以下这种方法

    Reference(T referent, ReferenceQueue<? super T> queue) {
this.referent = referent;
this.queue = (queue == null) ? ReferenceQueue.NULL : queue;
}

referent又是啥

    private T referent;         /* Treated specially by GC */

看到这个Treated specially。。。

。字眼了么

如今在看下ThreadLocal的get方法

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

先是取出Entey对象

        private Entry getEntry(ThreadLocal key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}

在看下,e.get()方法

好吧就是调用的reference的以下这种方法

    /**
* Returns this reference object's referent. If this reference object has
* been cleared, either by the program or by the garbage collector, then
* this method returns <code>null</code>.
*
* @return The object to which this reference refers, or
* <code>null</code> if this reference object has been cleared
*/
public T get() {
return this.referent;
}

JDK之ThreadLocal分析的更多相关文章

  1. JDK源码分析—— ArrayBlockingQueue 和 LinkedBlockingQueue

    JDK源码分析—— ArrayBlockingQueue 和 LinkedBlockingQueue 目的:本文通过分析JDK源码来对比ArrayBlockingQueue 和LinkedBlocki ...

  2. JDK 源码分析(4)—— HashMap/LinkedHashMap/Hashtable

    JDK 源码分析(4)-- HashMap/LinkedHashMap/Hashtable HashMap HashMap采用的是哈希算法+链表冲突解决,table的大小永远为2次幂,因为在初始化的时 ...

  3. JDK源码分析(三)—— LinkedList

    参考文档 JDK源码分析(4)之 LinkedList 相关

  4. JDK源码分析(一)—— String

    dir 参考文档 JDK源码分析(1)之 String 相关

  5. JDK源码分析(2)LinkedList

    JDK版本 LinkedList简介 LinkedList 是一个继承于AbstractSequentialList的双向链表.它也可以被当作堆栈.队列或双端队列进行操作. LinkedList 实现 ...

  6. 【JDK】JDK源码分析-LinkedHashMap

    概述 前文「JDK源码分析-HashMap(1)」分析了 HashMap 主要方法的实现原理(其他问题以后分析),本文分析下 LinkedHashMap. 先看一下 LinkedHashMap 的类继 ...

  7. 【JDK】JDK源码分析-HashMap(1)

    概述 HashMap 是 Java 开发中最常用的容器类之一,也是面试的常客.它其实就是前文「数据结构与算法笔记(二)」中「散列表」的实现,处理散列冲突用的是“链表法”,并且在 JDK 1.8 做了优 ...

  8. 【JDK】JDK源码分析-TreeMap(2)

    前文「JDK源码分析-TreeMap(1)」分析了 TreeMap 的一些方法,本文分析其中的增删方法.这也是红黑树插入和删除节点的操作,由于相对复杂,因此单独进行分析. 插入操作 该操作其实就是红黑 ...

  9. 【JDK】JDK源码分析-Vector

    概述 上文「JDK源码分析-ArrayList」主要分析了 ArrayList 的实现原理.本文分析 List 接口的另一个实现类:Vector. Vector 的内部实现与 ArrayList 类似 ...

随机推荐

  1. @CrossOrigin 跨域注解

    在spring 4.2后,提供了跨域注解@CrossOrigin https://spring.io/guides/gs/rest-service-cors/ Enabling CORS Contro ...

  2. CentOS7安装Gnome GUI图形界面

    CentOS7安装Gnome GUI图形界面  最小化安装了.当时没 注意,后面一步步安装完了,结果直接启动到命令行模式了. 晕,又不想重新安装,直接想从命令行模式安装.在网上找了半天,终于找到一点小 ...

  3. 转:【AI每日播报】从TensorFlow到Theano:横向对比七大深度学习框架

    http://geek.csdn.net/news/detail/139235 说到近期的深度学习框架,TensorFlow火的不得了,虽说有专家在朋友圈大声呼吁,不能让TensorFlow形成垄断地 ...

  4. Selenium webdriver Java 查找元素

    1.简单查找 By ID: WebElement element=driver.findElement(By.id("userId")); By Name:WebElement e ...

  5. java常用英语单词

    abstract (关键字) 抽象 ['.bstr.kt] access vt.访问,存取 ['.kses]'(n.入口,使用权) algorithm n.算法 ['.lg.riem] annotat ...

  6. C语言面向对象编程(五):单链表实现(转)

    这里实现的单链表,可以存储任意数据类型,支持增.删.改.查找.插入等基本操作.(本文提供的是完整代码,可能有些长.) 下面是头文件: #ifndef SLIST_H #define SLIST_H # ...

  7. Linux下默认的目录介绍

    目录/文件 用途 来源 / /处于Linux文件系统树形结构的最顶端,它是Linux文件系统的入口,所有的目录.文件.设备都在/之下. - /bin 该目录存放着系统最常用的最重要的命令,相当于DOS ...

  8. Android布局中match_parent和fill_parent的差别

    今天在做项目的一个新功能的时候,从网上查找资源,发现android2.2中出现的MATCH_PARENT感到不明确.过去仅仅有FILL_PARENT和WRAP_CONTENT那么match_paren ...

  9. CentOS7下利用init.d启动脚本实现tomcat开机自启动

    在之前的博文中已经对CentOS7下通过tomcat进行WEB系统的发布进行了介绍,今天将利用init.d启动脚本,将服务脚本加入到开机启动服务队列,实现tomcat服务的开机启动. 1. 环境准备 ...

  10. kafka 部分问题处理记录

    转载请注明原创地址:http://www.cnblogs.com/dongxiao-yang/p/7600561.html 一  broker启动后ReplicaFetcherThread OOM 版 ...