Error message here!

Hide Error message here!

忘记密码?

Error message here!

请输入正确邮箱

Hide Error message here!

密码丢失?请输入您的电子邮件地址。您将收到一个重设密码链接。

Error message here!

返回登录

Close

被面试官吊打系列之Java基础 之 ThreadLocal 源码分析

CanntBelieve 2020-04-09 01:31:00 阅读数:32 评论数:0 点赞数:0 收藏数:0

其实 ThreadLocal 命名不太好,应当改名叫做 thread-local variable,即线程本地变量。一个ThreadLocal实例就是一个线程本地变量。它的特点是就是 任何时候同一个线程可以通过这个 ThreadLocal实例变量 访问到绑定的值 (其实有点绕);需要注意的是 init方法,它默认什么都不做,通常我们需要覆写它,当然,这个完全是按照需要来定的。 每次线程执行get的时候,如果发现其内部的map还未创建,那么就创建,并且调用init初始化;

———— 更新,这个说法是不太准确的,虽然 ThreadLocalMap是ThreadLocal的静态内部类,但是并不会对每个ThreadLocal 创建一个ThreadLocalMap, 而是整个jvm所有ThreadLocal 共用一个ThreadLocalMap~!

浅尝辄止容易,深入浅出就很难。很多时候只要面试官多问几句,自己就会陷入懵逼状态了; 不是不懂,只是总有一些地方说不清道不明~.. 没有十分的清清楚楚明明白白,不敢乱说,干脆就糊弄一下;但是就会被面试官发现马脚。所以还是需要认真的研读一些源码。


源码大致分析
1 我之前以为是Thread 对ThreadLocal提供的支持, 其实不是的,跟Thread 几乎没什么关系。其实 ThreadLocal内部有一个静态来 ThreadLocalMap, 这个可谓是重中之重; 理解了它就理解了ThreadLocal。 ThreadLocalMap首先它是静态的,意味着它整个jvm中只需要创建一次!~ ThreadLocalMap顾名思义 是ThreadLocal的Map,但是它并不是内部有一个map字段之类的,也不是它继承了HashMap之类的已有的Map实现,它是自己重新实现了map的逻辑; 基本上就是内部一个数组Entry[] table,key的类型固定是ThreadLocal,value当然是不固定的,是静态内部类ThreadLocalMap.Entry, 这个Entry 非常的特别,继承了WeakReference<ThreadLocal<?>>; 然后扩容的时候,也是每次*2; 和HashMap的差别还是蛮大的;先到这里,没有时间研究透彻..xxx(这个大概也是不直接使用HaspMap的原因吧)
(WeakReference 确保了线程终止之后,对应的线程变量即ThreadLocal实例能够被回收~!)

2 使用的时候, 我们直接调用 ThreadLocal实例对象(比如tl)的的get方法,如果是整个jvm中第一次,那么创建ThreadLocalMap,然后 tl 调用 getEntry (不知道为什么没有get方法,而是提供了一个 getEntry方法),参数是自身,也就是ThreadLocal实例对象tl, 这个有点奇怪,不过也是可以理解的,那么getEntry方法内部计算 tl 的hash值等,找到它在map中的数组中对应的槽位等,然后返回; 如果调用tl的set方法,也是类似的,像hashMap的内部一样, 有一个通过key计算hash值的过程。 remove也是一样, 需要把tl对应的entry 删除掉。

换句话说,每一个 ThreadLocal实例对象 其实是对应了 ThreadLocalMap实例对象的一个 Entry, 每次ThreadLocal实例对象的操作其实是在操作这个Entry~!

 

使用场景呢?
就是需要在线程上绑定一些变量的时候,非常有用; 如果一个线程需要执行很多很多的操作,可能跨域了很多个方法、类级别的调用,同时可能耗时也比较长, 然后; 有点类似全局变量,但它又是线程安全的。
具体来说,当很多线程需要多次使用同一个对象,并且需要该对象具有相同初始化值的时候最适合使用ThreadLocal。最常见的ThreadLocal使用场景为 用来解决 数据库连接、Session管理等。

 

ThreadLocal VS 多线程锁

乍看起来和多线程的一些锁有点类似,但是差别非常大,使用场景完全不同。可以说,ThreadLocal提供了一个单线程的环境,从而它是线程安全的变量,它避免了多线程的线程安全问题;get、set、remove 的时候 当然是不需要考虑并发问题的, 因为都只将在当前线程中调用; ThreadLocal为每个线程都提供了变量的副本,使得每个线程在某一时间訪问到的并非同一个对象,这样就隔离了多个线程对数据的数据共享

package java.lang;
import java.lang.ref.*;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
/**
* This class provides thread-local variables. These variables differ from
* their normal counterparts in that each thread that accesses one (via its
* {@code get} or {@code set} method) has its own, independently initialized
* copy of the variable. {@code ThreadLocal} instances are typically private
* static fields in classes that wish to associate state with a thread (e.g.,
* a user ID or Transaction ID).
*
* <p>For example, the class below generates unique identifiers local to each
* thread.
* A thread's id is assigned the first time it invokes {@code ThreadId.get()}
* and remains unchanged on subsequent calls.
这个类提供了线程本地变量。 这些变量与普通的对应变量不同的是,每个访问变量的线程(通过其{@code get}或{@code set}方法)都有自己的、独立的初始化变量副本。 {@code ThreadLocal}实例通常是类中希望将状态与线程关联的私有静态字段(例如,用户ID或事务ID)。<p>例如,下面的类会生成每个线程的本地唯一标识符。线程的id在第一次调用{@code ThreadId.get()}时被分配,并在后续调用时保持不变。
* <pre>
* import java.util.concurrent.atomic.AtomicInteger;
*
* public class ThreadId {
* // Atomic integer containing the next thread ID to be assigned
* private static final AtomicInteger nextId = new AtomicInteger(0);
*
* // Thread local variable containing each thread's ID
* private static final ThreadLocal&lt;Integer&gt; threadId =
* new ThreadLocal&lt;Integer&gt;() {
* &#64;Override protected Integer initialValue() {
* return nextId.getAndIncrement();
* }
* };
*
* // Returns the current thread's unique ID, assigning it if necessary
* public static int get() {
* return threadId.get();
* }
* }
* </pre>
* <p>Each thread holds an implicit reference to its copy of a thread-local
* variable as long as the thread is alive and the {@code ThreadLocal}
* instance is accessible; after a thread goes away, all of its copies of
* thread-local instances are subject to garbage collection (unless other
* references to these copies exist).
*
* @author Josh Bloch and Doug Lea
* @since 1.2
*/
public class ThreadLocal<T> {
/**
* ThreadLocals rely on per-thread linear-probe hash maps attached
* to each thread (Thread.threadLocals and
* inheritableThreadLocals). The ThreadLocal objects act as keys,
* searched via threadLocalHashCode. This is a custom hash code
* (useful only within ThreadLocalMaps) that eliminates collisions
* in the common case where consecutively constructed ThreadLocals
* are used by the same threads, while remaining well-behaved in
* less common cases.
*/
private final int threadLocalHashCode = nextHashCode();
/**
* The next hash code to be given out. Updated atomically. Starts at
* zero.
*/
private static AtomicInteger nextHashCode =
new AtomicInteger();
/**
* The difference between successively generated hash codes - turns
* implicit sequential thread-local IDs into near-optimally spread
* multiplicative hash values for power-of-two-sized tables.
*/
private static final int HASH_INCREMENT = 0x61c88647;
/**
* Returns the next hash code.
*/
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
/**
* 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}.
*
* <p>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.
返回当前线程本地变量的 "初始值"。 这个方法将在线程第一次使用{@link #get}方法访问该变量时被调用,除非该线程之前调用了{@link #set}方法,在这种情况下,{@code initialValue}方法不会被调用。 通常情况下,这个方法在每个线程中最多调用一次,但是在后续调用{@link #remove}和{@link #get}的情况下,这个方法可能会被再次调用。 <p>这个实现只需返回{@code null};如果程序员希望线程本地变量的初始值不是{@code null},那么必须子类化{@code ThreadLocal},并重载这个方法。 通常情况下,会使用一个匿名的内部类。
*
* @return the initial value for this thread-local
*/
protected T initialValue() {
return null;
}
/**
* Creates a thread local variable. The initial value of the variable is
* determined by invoking the {@code get} method on the {@code Supplier}.
创建一个线程的本地变量,变量的初始值由调用{@code Supplier}上的{@code get}方法决定。变量的初始值由调用{@code get}方法决定。
*
* @param <S> the type of the thread local's value
* @param supplier the supplier to be used to determine the initial value
* @return a new thread local variable
* @throws NullPointerException if the specified supplier is null
* @since 1.8
*/
SuppliedThreadLocal 也是内部的静态final类:
public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
return new SuppliedThreadLocal<>(supplier);
}
/**
* Creates a thread local variable.
* @see #withInitial(java.util.function.Supplier)
*/
public ThreadLocal() {
}
/**
* 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.
返回当前线程本地变量的副本中的值。 如果这个变量对当前线程没有值,那么它首先被初始化为调用{@link #initialValue}方法返回的值。
*
* @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) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
/**
* 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;
}
/**
* 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.
将当前线程的本地变量的副本设置为指定的值。 大多数子类不需要覆盖这个方法,只需要依靠{@link #initialValue}方法来设置线程本地变量的值。
*
* @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);
}
/**
* Removes the current thread's value for this thread-local
* variable. If this thread-local variable is subsequently
* {@linkplain #get read} by the current thread, its value will be
* reinitialized by invoking its {@link #initialValue} method,
* unless its value is {@linkplain #set set} by the current thread
* in the interim. This may result in multiple invocations of the
* {@code initialValue} method in the current thread.
删除当前线程对这个线程本地变量的值。 如果这个线程本地变量随后被当前线程{@linkplain #get read},它的值将通过调用它的{@link #initialValue}方法重新初始化,除非它的值被当前线程{@linkplain #set set}。 这可能导致在当前线程中多次调用{@code initialValue}方法。
*
* @since 1.5
*/
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
/**
* 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;
}
/**
* 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
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
/**
* Factory method to create map of inherited thread locals.
* Designed to be called only from Thread constructor.
*
* @param parentMap the map associated with parent thread
* @return a map containing the parent's inheritable bindings
*/
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
return new ThreadLocalMap(parentMap);
}
/**
* Method childValue is visibly defined in subclass
* InheritableThreadLocal, but is internally defined here for the
* sake of providing createInheritedMap factory method without
* needing to subclass the map class in InheritableThreadLocal.
* This technique is preferable to the alternative of embedding
* instanceof tests in methods.
*/
T childValue(T parentValue) {
throw new UnsupportedOperationException();
}
/**
* An extension of ThreadLocal that obtains its initial value from
* the specified {@code Supplier}.
*/
static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {
private final Supplier<? extends T> supplier;
SuppliedThreadLocal(Supplier<? extends T> supplier) {
this.supplier = Objects.requireNonNull(supplier);
}
@Override
protected T initialValue() {
return supplier.get();
}
}
/**
* 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.
ThreadLocalMap是一个自定义的哈希map,只适用于维护线程本地值。在ThreadLocal类之外,没有任何操作被导出。该类是封装私有的,允许在类Thread中声明字段。 为了帮助处理非常大的和长时间的使用,哈希表条目使用WeakReferences作为键值。但是,由于不使用引用队列,所以只有当表开始用完空间时,陈旧的条目才会被保证删除。
*/
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.
这个哈希map中的入口条目扩展了WeakReference,使用它的主ref字段作为键(总是一个ThreadLocal对象)。 注意,空键(即 entry.get() == null)意味着该键不再被引用,因此该条目可以从表中删除。 这样的条目在下面的代码中被称为 "陈旧的条目"。
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = ;
/**
* 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 = ;
/**
* The next size value at which to resize.
*/
private int threshold; // Default to 0
/**
* Set the resize threshold to maintain at worst a 2/3 load factor.
*/
private void setThreshold(int len) {
threshold = len * / ;
}
/**
* Increment i modulo len.
*/
private static int nextIndex(int i, int len) {
return ((i + < len) ? i + : );
}
/**
* Decrement i modulo len.
*/
private static int prevIndex(int i, int len) {
return ((i - >= ) ? i - : len - );
}
/**
* 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 - );
table[i] = new Entry(firstKey, firstValue);
size = ;
setThreshold(INITIAL_CAPACITY);
}
/**
* 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 - );
Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}
....
}

 


参考:
https://blog.csdn.net/ityouknow/article/details/90709371
https://blog.csdn.net/liuhaiabc/article/details/78077529
https://www.cnblogs.com/yxysuanfa/p/7125761.html

 

版权声明
本文为[CanntBelieve]所创,转载请带上原文链接,感谢
https://www.cnblogs.com/FlyAway2013/p/12664189.html