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. NYOJ 1058 部分和问题 【DFS】

    部分和问题 时间限制:1000 ms  |  内存限制:65535 KB 难度:2 描写叙述 给定整数a1.a2........an,推断能否够从中选出若干数.使它们的和恰好为K. 输入 首先,n和k ...

  2. avro序列化详细操作

    Intellij 15.0.3 Maven avro 1.8.0 Avro是一个数据序列化系统. 它提供以下: 1 丰富的数据结构类型 2 快速可压缩的二进制数据形式 3 存储持久数据的文件容器 4 ...

  3. Java虚拟机中的栈和堆的定义和区别

    在函数中定义的一些基本类型的变量和对象的引用变量都在函数的栈内存中分配. 当在一段代码块定义一个变量时,Java就在栈中为这个变量分配内存空间,当超过变量的作用域后,Java会自动释放掉为该变量所分配 ...

  4. ajax不运行success回调而是运行error回调

    调试代码遇到一个问题,就是前台运行删除操作后,controller返回数据,但前台接收时,ajax不运行success回调,总是弹出失败的对话框.接收数据类型是json. 先看看我的前台代码. if ...

  5. [ACM] POJ 2151 Check the difficulty of problems (概率+DP)

    Check the difficulty of problems Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 4748   ...

  6. 一个简单的JS函数,用于判断文本是否数字

    /****************************************************** 判断是否是数字(整数,小数均可,不包括负数)* 2014年10月10日22:38:19* ...

  7. jQuery控制form表单元素聚焦

      CreateTime--2017年5月28日08:57:16Author:Marydon jQuery使form表单的第一个文本框聚焦 /** * 使form表单的第一个文本框聚焦 */ func ...

  8. React Native : 自定义视图

    代码地址如下:http://www.demodashi.com/demo/11686.html 这次我们要做的仿 新闻头条 的首页的顶部标签列表,不要在意新闻内容. 请求数据 首先做顶部的目录视图,首 ...

  9. How to learn a new technology

    是什么?为什么会出现? 这一阶段主要是对该技术有一个整体了解,他所解决的是什么问题,他的整体结构等. 怎么做? 最简单的是找一个上手视频,因为视频是非常直观的展示了技术的使用.先学会用是最根本的,对于 ...

  10. js使用ctrl+s保存表单提升用户体验

    本质上是监控ctrl+s 然后触发相应事件 <script language="JavaScript"> //Ctrl+s保存 document.onkeydown=f ...