/**
- Creates a thread local variable.
- @see #withInitial(java.util.function.Supplier)
*/
public ThreadLocal() {
}
2.2 ThreadLocalMap类
2.2.1 Entry
- 源码可以看到Entry这个类是弱引用的类型。
- key放ThreadLocal,value放存放的内容。
/**
- 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;
}
}
2.2.2 构造方法
- 创建一个长度为16的Entry数组,然后存放的位置用hashcode和15做与运算得到,再保存内容。
/**
- ThreadLocalMap is a customized hash map suitable only for
- maintaining thread local values. No operations are exported
- outside of the ThreadLocal class. The class is package private to
- allow declaration of fields in class Thread. To help deal with
- very large and long-lived usages, the hash table entries use
- WeakReferences for keys. However, since reference queues are not
- used, stale entries are guaranteed to be removed only when
- the table starts running out of space.
*/
static class ThreadLocalMap {
/**
- The initial capacity – MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
- The table, resized as necessary.
- table.length MUST always be a power of two.
*/
private Entry[] table;
/**
- The number of entries in the table.
*/
private int size = 0;
/**
- 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);
}
.
.
}
2.2.3 set(ThreadLocal<?> key, Object value)
- 如果计算的位置已经有内容了,就覆盖,否则就新建一个Entry存放,再判断是否达到阈值,不够就扩容。
/**
- 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();
}
2.2.4 setInitialValue()
- 初始化空Entry,因为有的线程ThreadLocal一开始没有存东西,但调用了get方法,这时候没内容,但还是先占个坑,返回null。
/**
- Returns the current thread’s “initial value” for this
- thread-local variable. This method will be invoked the first
- time a thread accesses the variable with the {@link #get}
- method, unless the thread previously invoked the {@link #set}
- method, in which case the {@code initialValue} method will not
- be invoked for the thread. Normally, this method is invoked at
- most once per thread, but it may be invoked again in case of
- subsequent invocations of {@link #remove} followed by {@link #get}.
-
This implementation simply returns {@code null}; if the
- programmer desires thread-local variables to have an initial
- value other than {@code null}, {@code ThreadLocal} must be
- subclassed, and this method overridden. Typically, an
- anonymous inner class will be used.
- @return the initial value for this thread-local
*/
protected T initialValue() {
return null;
}
/**
- Variant of set() to establish initialValue. Used instead
- of set() in case user has overridden the set() method.
- @return the initial value
*/
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
2.2.5 getEntry(ThreadLocal<?> key)
- 利用hashcode找到对应的Entry,如果一次命中找到最好,但扩容过可能不可以一次命中,就要执行 getEntryAfterMiss 方法找。
/**
- Get the entry associated with key. This method
- itself handles only the fast path: a direct hit of existing
- key. It otherwise relays to getEntryAfterMiss. This is
- designed to maximize performance for direct hits, in part
- by making this method readily inlinable.
- @param key the thread local object
- @return the entry associated with key, or null if no such
*/
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);
}
/**
- Version of getEntry method for use when key is not found in
- its direct hash slot.
- @param key the thread local object
- @param i the table index for key’s hash code
- @param e the entry at table[i]
- @return the entry associated with key, or null if no such
*/
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
Entry[] tab = table;
int len = tab.length;
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级安卓工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年最新Android移动开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Android)
最后
g-uicPPQ1T-1710501873604)]
[外链图片转存中…(img-Jc0ykZpU-1710501873605)]
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Android)
[外链图片转存中…(img-xpnvDvvG-1710501873605)]
最后
想要了解更多关于大厂面试的同学可以**点击这里免费获取《面试文档》**除此之外,我也分享一些免费的优质资源,包括:Android学习PDF+架构视频+源码笔记,高级架构技术进阶脑图、Android开发面试专题资料,高级进阶架构资料 这几块的内容。分享给大家,非常适合近期有面试和想在技术道路上继续精进的朋友。快来获取学习资料吧~