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. 一起來玩鳥 Starling Framework(5)Multi-Touch

    這篇來談談Starling的Multi-Touch.前一篇也提到,Multi-Touch一樣是監聽TouchEvent.TOUCH,然後由TouchEvent的e.getTouches()取回多點的資 ...

  2. Python中lambda使用简易教程

    例如: f = lambda x: x+x #lambda后的x为参数 print f(3) >>6 等价于 def func(x): return x+x print func(3) 与 ...

  3. DataGridView拖动到TreeView

    很多时候我们会有这样的需求:一个窗体中有两个GRID,两个GRID中数据表结构差不多,我们要把一个GRID中的数据加入到另一个GRID中.一般的做法是新增一个导入或导出按钮,选择目标行后,通过按钮来触 ...

  4. [Javascript] Intercept property access with Javascript Proxy

    A Javascript Proxy object is a very interesting es6 feature, that allows you to determine behaviors ...

  5. 基于Maven的SpringBoot项目实现热部署的两种方式

    转载:http://blog.csdn.net/tengxing007/article/details/72675168 前言 JRebel是JavaEE中比较流行的热部署插件,可快速实现热部署,节省 ...

  6. Docker默认存储路径修改

    Docker默认存储路径: # docker info...... Data loop file: /var/lib/docker/devicemapper/devicemapper/data.... ...

  7. S6:组合模式 Composite

    将对象组合成树形结构以表示整体-部分的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性. UML: 示例代码:透明组合:叶节点和子节点具有相同的接口 abstract class Com ...

  8. C、C++文件操作大全

    基于C的文件操作  在ANSI C中,对文件的操作分为两种方式,即流式文件操作和I/O文件操作,下面就分别介绍之. 一.流式文件操作  这种方式的文件操作有一个重要的结构FILE,FILE在stdio ...

  9. antd-design LocaleProvider国际化

    1.LocaleProvider 使用 React 的 context 特性,只需在应用外围包裹一次即可全局生效. import { LocaleProvider } from 'antd'; imp ...

  10. 切换默认Activity和Fragment的动画

    Activity中 public void click(View view){ Intent intent = new Intent(); intent.setClass(this, TwoActiv ...