ThreadLocal的使用
在多线程的使用场景下,因资源竞争而出现线程安全问题,一般情况可以通过加锁去解决.但在一些场景下,涉及的数据不能进行共享,需要线程封闭.
1 关于SimpleDateFormat的线程安全案例
public class SimpleDateFormatTest1 {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static class ParseDate implements Runnable {
private int i;
public ParseDate(int i) {
this.i = i;
}
@Override
public void run() {
try {
Date t = sdf.parse("2021-10-07 09:40:" + i % 60);
System.out.println(Thread.currentThread().getName() + " : " + t);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
es.execute(new ParseDate(i));
}
}
}
方法解析异常, 跟踪代码,发现SimpleDateFormat.parse方法不是线程安全的,在多线程环境下,共享变量导致出现解析异常.
常用的解决方法:
-
1 加锁, 即在parse方法前后加锁,以此来保证每次解析时使用的变量正确.
-
2 要使用就创建一个新对象. 即每次使用来重新new一个对象,保证一个对象只使用一次.(此方法会消耗大量内存,切后期不好维护)
-
3 使用ThreadLocal包裹SimpleDateFormat对象,保证每个线程之间都有一份相互独立的对象.
2 SimpleDateFormat的线程问题优化
public class SimpleDateFormatTest2 {
private static final ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<>();
public static class ParseDate implements Runnable {
private int i;
public ParseDate(int i) {
this.i = i;
}
@Override
public void run() {
try {
if (sdf.get() == null) {
sdf.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
Date t = sdf.get().parse("2021-10-07 09:40:" + i % 60);
System.out.println(Thread.currentThread().getName() + " : " + t);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
es.execute(new ParseDate(i));
}
}
}
3 ThreadLocal的原理
1 查看源码发现,ThreadLocal的对象存储在ThreadLocalMap对象中.
public class ThreadLocal<T> {
/**
* 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) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
....
}
2 进一步发现ThreadLocalMap是代表当前线程对象Thread内中threadLocals
public class ThreadLocal<T> {
/**
* 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;
}
....
}
public class Thread implements Runnable {
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
...
}
3 ThreadLocalMap是ThreadLocal内部定义的静态内部类
public class ThreadLocal<T> {
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.
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
// 与当前ThreadLocal相关的对象值
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
// 初始容量 且必须为2的倍数
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
// 存放信息的数组, 数组长度必须为2的倍数
private Entry[] table;
/**
* The number of entries in the table.
*/
// 数组的大小
private int size = 0;
/**
* The next size value at which to resize.
*/
// 扩容的阈值 默认为0
private int threshold; // Default to 0
/**
* Set the resize threshold to maintain at worst a 2/3 load factor.
*/
// 设置阈值为数组长度的2/3
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
/**
* Increment i modulo len.
*/
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
/**
* Decrement i modulo len.
*/
private static int prevIndex(int i, int len) {
return ((i - 1 >= 0) ? i - 1 : len - 1);
}
/**
* 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的构造器, i是经过ThreadLocal内部一个变量threadLocalHashCode计算而来的一个索引位置
// ThreadLocalMaps是一个懒加载构造器, 仅当创建了一个entry对象且put操作时才生效
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);
}
....
}
根据源码信息可得知,当创建了一个ThreadLocalMap对象, 在其内部是创建了Entry类型的数组,Entry是类似Map的Key-Value结构, Key是当前ThreadLocal对象计算的hashcode值,Value就是需要保存的线程变量副本(如上SimpleDateFormat对象). key初始化为16, 阈值为数组长度的2/3, Entry有一个弱引用指向ThreadLocal对象.
由此可知,每个Thread内部都维护了ThreadLocalMap对象,在创建一个ThreadLocal后, 等于把当前的ThreadLocal信息存放到Thread内部的ThreadLocalMap中.
4 ThreadLocal的相关方法
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);
}
/**
* 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);
}
由源码可知, set方法中获取ThreadLocalMap对象,如果对象不存在,则创建一个ThreadLocalMap, 存在则将ThreadLocalMap存入map中,Key为ThreadLocal当前对象, Value就是我们存的对象值.
get方法
public T get() {
Thread t = Thread.currentThread();
// 获取当前线程的ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
// 如果不为null,则返回value
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
// Map不存在或者找不到value值,则调用setInitialValue,进行初始化
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
ThreadLocalMap map = getMap(t);
if (map != null)
// 如果不为空,则设置值
map.set(this, value);
else
// 如果当前Map为null,就创建一个ThreadLocalMap保存
createMap(t, value);
return value;
}
protected T initialValue() {
return null;
}
每个线程内部都有一个ThreadLocalMap对象,当线程需要添加ThreadLocal对象时,都是保存到代表每个线程私有变量的ThreadLocalMap中,所以线程与线程间不会互相干扰。
5 哈希冲突问题
ThreadLocalMap本质是一个Entry类型的数组, 所有Map都需要解决哈希冲突问题.上面构造中的i就是ThreadLocal存放在ThreadLocalMap中的索引位置值.
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
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();
/**
* Returns the next hash code.
*/
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
public final int getAndAdd(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta);
}
....
}
由上代码可知, ThreadLocal会根据nextHashCode生成一个int值,作为哈希值. 再根据哈希值和数组长度-1求和.(数组的长度总是2的倍数,减一的话就可以保证低N位都是1), 从而获取哈希值的低N位,在获取数组中的索引位置.
ThreadLocalMap解决方法
/**
* 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);
// 如果要存放的i位置有数据,就说明发生了哈希冲突
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
// 如果是同一个ThreadLocal对象,就直接覆盖
if (k == key) {
e.value = value;
return;
}
// 如果key为null,则替换它的位置
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
// 否则就nextIndex(i, len),去找下一个位置
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
ThreadLocalMap在set值是进行判断, 根据i位置是否有数据判断, 如果存在, 说明存在哈希冲突,则判断是否是同一个对象,是就直接覆盖,为null则替换,否则就往后移动一位,继续判断查询.
6 内存泄露问题
因为TheadLocal变量是维护在Thread类内, 如果当前线程存活,变量中的对象的引用就一直存在.
即将TheadLocal置为null,不能解决对象不被java垃圾回收的问题,从而导致不能使用的内存越来越大,最后抛出内存泄露异常.
/**
* 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.
*
* @since 1.5
*/
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
/**
* Remove the entry for key.
*/
private void remove(ThreadLocal<?> key) {
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)]) {
if (e.get() == key) {
e.clear();
expungeStaleEntry(i);
return;
}
}
}
public void clear() {
this.referent = null;
}
解决方法:
TheadLocal对象调用remove方法, 会将referent和value都被设置为null,这样导致内存不能访问达到,java垃圾回收会回收这片内存,从而解决内存泄漏问题。
4 ThreadLocal使用场景
1 线程间数据隔离,各个线程使用自己的变量副本,互不影响.
2 Spring事务管理器中就是采用ThreadLocal来管理事务.
参考文档:
https://blog.csdn.net/qq_25448409/article/details/96780095
https://blog.csdn.net/qq_27276045/article/details/105330266