ThreadLocal 设计模式浅谈

时间:2022-03-20 17:54:08

部分代码:ThreadLocal中 的get方法, 获得的是当前线程相关的对象

/**
* 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.
*
* @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)
return (T)e.value;
}
return setInitialValue();
}

同理,对于 set方法亦是如此

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

ThreadLocal 是隶属于 Thread的一个变量, Thread类的部分源码:

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

ThreadLocal 模式至少通过两方面, 做到线程安全:

1, ‘纵向隔离’, 即跟Thread的数据结构有关, 每个线程访问自己独特的ThreadLocalMap。

2,‘横向隔离’, 即同一线程中,不同的ThreadLocal实例操作的对象之间隔离,这有ThreadLocalMap在存储时采用ThreadLocal实例作为key来保证。

ThreadLocal与synchronized两种方式完成线程安全不同之处:

前者是‘用空间换时间’, 后者是‘用时间换空间’。

ThreadLocal最适合的场景:

同一线程中,不同开发层次*享数据。

使用ThreadLocal模式主要步骤:

1,建立类, 并封装一个静态的ThreadLocal变量, 以做成共享环境。

2,在类中实现get/set 访问静态ThreadLocal变量的静态方法。

使用ThreadLocal模式的好处:

可以对执行逻辑和执行数据进行有效解耦。因为一般情况下,对象之间的协作是通过参数和返回值来进行消息传递。而ThreadLocal模式打破了这种依赖, 避免在编程层次之间形成数据依赖。