文章目录
ThreadLocal部分源码(jdk8)
private final int threadLocalHashCode = nextHashCode();
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;
get()
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();
}
当调用get方法获取值时,获取的是一个map中的某一个entry的value值。
而这个map是:
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
map是线程中的一个属性值:
ThreadLocal.ThreadLocalMap threadLocals = null;
,ThreadLocalMap 为ThreadLocal的一个静态内部类
上述从map中获取value时,执行map.getEntry(this);
,其中这个this指的是当前这个ThreadLocal对象,所以这个map即ThreadLocalMap ,key类型为ThreadLocal。
总结
个人理解:
以Thread的角度来看,使用了一个map用来存储这个线程中的对象,key为ThreadLocal对象,value为实际想存储的对象。也就是说,一个线程可以存多个对象,通过不同的ThreadLocal对象进行区分实际存储的对象。
以ThreadLocal的角度来看,ThreadLocal变量本身不存数据,只是提供了get(), set()方法去操作实际的数据。
使用
使用场景
- 线程隔离
ThreadLocal中的数据只属于当前线程,其本地值对别的线程不可见,在多线程下,可以防止自己的变量被其他线程篡改。另外,由于各个线程之间的数据相互隔离,避免了同步加锁带来的性能损失,大大提升了并发性的性能。 - 跨函数传递数据
通常用于同一个线程内,跨类、跨方法传递数据时,如果不用ThreadLocal,那么相互之间的数据传递势必要靠返回值和参数,这样无形之中增加了这些类或者方法之间的耦合度。
线程隔离
例如:数据库连接独享
private static final ThreadLocal threadSession = new ThreadLocal();
public static Session getSession() throws InfrastructureException {
Session s = (Session) threadSession.get();
try {
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
return s;
}
一个Session代表一个数据库连接。
一般来说,完成数据库曹祖之后程序会将Session关闭,从而节省数据库连接资源。如果Session的使用方式为共享而不是独占,在这种情况下,Session是多线程共享使用的,如果某个线程使用完成后直接将Session关闭,其他线程在操作Session时就会报错。所以通过ThreadLocal非常简单地实现了数据库连接的安全使用。
跨函数数据传递
例如:
(1)用来传递请求过程中的用户ID。
(2)用来传递请求过程中的用户会话(Session)。
(3)用来传递HTTP的用户请求实例HttpRequest。
(4)其他需要在函数之间频繁传递的数据
ThreadLocal其他源码(jdk8)
内部类
SuppliedThreadLocal
/**
* 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
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. */
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 = 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;
/**
* The next size value at which to resize.
*/
private int threshold; // Default to 0
//......
}
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);
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
remove()
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
先取到当前线程的ThreadLocalMap ,调用ThreadLocalMap 对应的remove方法,其中this,就是当前ThreadLocal对象。(从前面的ThreadLocalMap 类来看,该类并不是继承了map,而是自己单独实现的一个map)
initialValue
protected T initialValue() {
return null;
}
ThreadLocal中该方法直接返回了null,如果初始值不想为null,则可以自己继承ThreadLocal重写该方法。
其实上述提到的内部类SuppliedThreadLocal,就继承了ThreadLocal,并且重写了该方法。
使用:ThreadLocal定义了一个静态工厂方法withInitial,返回的就是SuppliedThreadLocal,传参可以结合Lambda表达式。
public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
return new SuppliedThreadLocal<>(supplier);
}
例如:
ThreadLocal<User> userThreadLocal = ThreadLocal.withInitial(() -> new User());
ThreadLocalMap 源码
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;
// 根据key的hashcode,找到key在数组上的槽点i
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;
}
// 找到异常槽点:槽点被GC掉,重设Key值和Value值
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
// 没有找到现有的槽点,增加新的Entry
tab[i] = new Entry(key, value);
int sz = ++size;
// 清理key为null的无效Entry
// 没有可清理的Entry,并且现有条目数量大于扩容因子值,进行扩容
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
注意:static class Entry extends WeakReference<ThreadLocal<?>>
,定义的Entry是一个弱引用类型。
为什么是弱引用?举例:
public void funcA()
{
//创建一个线程本地变量
ThreadLocal local = new ThreadLocal<Integer>();
//设置值
local.set(100);
//获取值
local.get();
//函数末尾
}
当线程tn调用funcA(),会生成一个栈帧,结构大致如下:
当funcA()结束后,栈帧被销毁,那条强引用也就没有了。如果Entry中不是弱引用的话,则表示,一个不再被使用的对象,没有即使释放,那么就会造成内存泄漏。
使用ThreadLocal会发生内存泄漏的前提条件:
(1)线程长时间运行而没有被销毁。
(2)ThreadLocal引用被设置为null,且后续在同一Thread实例执行期间,没有发生对其他ThreadLocal实例的get(), set()或remove()操作。因为这些操作中会对map的key为null的entry进行清理,释放掉ThreadLocal弱引用为null的entry。
remove()
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;
}
}
}
其他ThreadLocal类
InheritableThreadLocal
根据名称来看,该类就是具有继承性质的一种ThreadLocal
源码
public class InheritableThreadLocal<T> extends ThreadLocal<T> {
/**
* Computes the child's initial value for this inheritable thread-local
* variable as a function of the parent's value at the time the child
* thread is created. This method is called from within the parent
* thread before the child is started.
* <p>
* This method merely returns its input argument, and should be overridden
* if a different behavior is desired.
*
* @param parentValue the parent thread's value
* @return the child thread's initial value
*/
protected T childValue(T parentValue) {
return parentValue;
}
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
}
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
}
从getMap()方法来看,InheritableThreadLocal中获取的变量存储在线程的inheritableThreadLocals属性中。ThreadLocal中获取的变量是存储在线程的threadLocals属性中:
// Thread的属性
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
该类除了重写两个有关map的方法,还重写的一个方法就是childValue()。
childValue
经过往上找该方法被调用的时机,来看什么操作会执行该方法:
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
初始化一个Thread时,调用init方法:
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name;
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
if (g == null) {
/* Determine if it's an applet or not */
/* If there is a security manager, ask the security manager
what to do. */
if (security != null) {
g = security.getThreadGroup();
}
/* If the security doesn't have a strong opinion of the matter
use the parent thread group. */
if (g == null) {
g = parent.getThreadGroup();
}
}
/* checkAccess regardless of whether or not threadgroup is
explicitly passed in. */
g.checkAccess();
/*
* Do we have the required permissions?
*/
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
g.addUnstarted();
this.group = g;
this.daemon = parent.isDaemon();
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;
setPriority(priority);
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
/* Set thread ID */
tid = nextThreadID();
}
其中this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
中对new出来的线程的inheritableThreadLocals属性进行了赋值。
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
return new ThreadLocalMap(parentMap);
}
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len];
for (int j = 0; j < len; j++) {
Entry e = parentTable[j];
if (e != null) {
@SuppressWarnings("unchecked")
ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}
大概就是将parentMap中的key-value遍历存在前面new的线程的map中。而这个parentMap就是当前线程中的inheritableThreadLocals属性
注意:要区分当前线程与new出来的线程。是在当前线程中new的线程,在这里当前线程就是父线程。
再细看赋值的条件:if (inheritThreadLocals && parent.inheritableThreadLocals != null)
需要参数inheritThreadLocals = true 且父线程的inheritableThreadLocals属性不为空。
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
init(g, target, name, stackSize, null, true);
}
该init方法中调用的init方法传参inheritThreadLocals=true。而该init方法都是在构造函数中被调用的。
所以只要是new出来的线程,传参中该值就为true。
对于parent.inheritableThreadLocals
属性值,在InheritableThreadLocal的creatMap方法中就是对inheritableThreadLocals进行的初始化,getMap方法获取的也是这个属性,所以,对于使用InheritableThreadLocal来存储线程的变量,只要是在线程中new Thread(),子线程就会有父线程之前存储的变量。
test
public class ThreadLocalTest {
static ThreadLocal threadLocal = new ThreadLocal<String>();
static ThreadLocal inheritableThreadLocal = new InheritableThreadLocal();
public static void main(String[] args) throws InterruptedException {
threadLocal.set("threadLocal variable");
inheritableThreadLocal.set("inherited parent variable");
System.out.println(threadLocal.get());
System.out.println(inheritableThreadLocal.get());
new MyThread().start();
Thread.sleep(1000);
inheritableThreadLocal.set("exchange parent variable");
new MyThread().start();
Thread.sleep(5000);
}
static class MyThread extends Thread{
public MyThread(){
}
@Override
public void run() {
System.out.println(threadLocal.get());
System.out.println(inheritableThreadLocal.get());
}
}
}
// 输出结果:
threadLocal variable
inherited parent variable
null
inherited parent variable
null
exchange parent variable
注意:线程中不再使用的ThreadLocal变量,要记得remove,避免内存泄漏