背景
近期在看netty源码,发现有个叫做FastThreadLocal的类,代码doc中写明此类的用途和ThreadLocal一样,都是维持线程独有的变量,但是速度会更快。于是产生了疑问:FastThreadLocal为什么比ThreadLocal更快?快在哪?基于这个疑问,对此做了性能测试,并基于此,分析了源码,找寻原因。
性能测试
在JDK中ThreadLocal主要用于多线程环境获取当前线程维护变量数据,用户不需要关心多线程的问题,因此用户在多线程的环境下也可以方便的使用它。以下测试内容基于考虑两种情况
- 在多线程情况下,访问同一个ThreadLocal或FastThreadLocal变量。
- 在单线程下,访问多个ThreadLocal或FastThreadLocal变量。
下面将对此两种情况分别做测试对比性能
1. 多线程访问同一个ThreadLocal或FastThreadLocal
代码如下:
/**
* 多线程访问同一ThreadLocal实例
*
*/
public static void testThreadLocalWithMultipleThreads() {
ThreadLocal<String> threadLocal = new ThreadLocal<>();
long start = System.currentTimeMillis();
Thread[] threads = new Thread[count];
for (int i = 0; i < count; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
threadLocal.set(Thread.currentThread().getName());
for (int j = 0; j < count; j++) {
threadLocal.get();
}
}
}, "Thread" + i);
threads[i].start();
}
long end = System.currentTimeMillis();
System.out.println("testThreadLocalWithMultipleThreads get:" + (end - start));
}
/**
* 多线程访问同一FastThreadLocal实例
*/
public static void testFastThreadLocalWithMultipleThreads() {
FastThreadLocal<String> threadLocal = new FastThreadLocal<>();
long start = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
new FastThreadLocalThread(new Runnable() {
@Override
public void run() {
threadLocal.set(Thread.currentThread().getName());
for (int j = 0; j < count; j++) {
threadLocal.get();
}
}
}, "Thread" + i).start();
}
long end = System.currentTimeMillis();
System.out.println("testFastThreadLocalWithMultipleThreads get:" + (end - start));
}
输出结果:
testThreadLocalWithMultipleThreads get:13800
testFastThreadLocalWithMultipleThreads get:11335
在此场景下,使用ThreadLocal和使用FastThreadLocal相差不大
2. 单线程访问多ThreadLocal或FastThreadLocal实例
测试代码如下:
/**
* 单线程访问多个ThreadLocal
*/
public static void testThreadLocalWithMultipleThreadLocal() {
ThreadLocal<String> threadLocal[] = new ThreadLocal[count];
for (int i = 0; i < count; i++) {
threadLocal[i] = new ThreadLocal<String>();
}
new Thread(new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
threadLocal[i].set("value" + i);
}
long middle = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
for (int j = 0; j < count; j++) {
threadLocal[i].get();
}
}
long end = System.currentTimeMillis();
System.out.println("testThreadLocalWithMultipleThreadLocal set:" + (middle - start) + ",get:" + (end - middle));
}
}).start();
}
/**
* 单线程访问多个FastThreadLocal
*/
public static void testFastThreadLocalWithMultipleFastThreadLocal() {
FastThreadLocal<String> threadLocal[] = new FastThreadLocal[count];
for (int i = 0; i < count; i++) {
threadLocal[i] = new FastThreadLocal<String>();
}
new FastThreadLocalThread(new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
threadLocal[i].set("value" + i);
}
long middle = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
for (int j = 0; j < count; j++) {
threadLocal[i].get();
}
}
long end = System.currentTimeMillis();
System.out.println("testFastThreadLocalWithMultipleFastThreadLocal set:" + (middle - start) + ",get:" + (end - middle));
}
}).start();
}
输出结果:
testThreadLocalWithMultipleThreadLocal set:68,get:21492
testFastThreadLocalWithMultipleFastThreadLocal set:61,get:8
在此场景下,使用FastThreadLocal的性能远高于使用ThreadLocal
原理分析
ThreadLocal机制
在使用ThreadLocal时,主要使用它的get和set方法,所以我们从这两个方法开始入手分析。
public void set(T value) {
Thread t = Thread.currentThread();
// 根据当前线程获取ThreadLocalMap, ThreadLocalMap是Thread的一个属性实例
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
从此方法可以看出,ThreadLocal的set方法,其实调用的是ThreadLocalMap的set方法,具体实现需要看ThreadLocalMap的实现。现在看下ThreadLocalMap是如何实现set方法的
private void set(ThreadLocal<?> key, Object value) {
// ThreadLocalMap内部通过一个Entry数组存储
Entry[] tab = table;
int len = tab.length;
// 通过ThreadLocal.threadLocalHashCode作为数组下标
int i = key.threadLocalHashCode & (len-1);
// 此处获取当前i下标中是否存有元素,若有则判断当前ThreadLocal实例是否为键,若是则直接赋值到当前i下标下,若不是,则继续找下一个下标作为i,直到e为空,即i达到size的值
// 此处size表示当前实际存储的下标,而数组长度len,为数组的长度,当前存储的数量小于len,一般在size达到len的一半时,将会对table进行扩容,扩容大小为元len的2倍;具体可查看rehash方法
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;
}
}
// 此时表示数组中已用的槽位没有空位,也没有当前ThreadLocal实例的槽位,扩展一个槽位
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
一般来说,ThreadLocalMap使用了一个数组来存储数据,类似于HashMap,每一个ThreadLoca在初始化时,分配一个threadLocalHashCode,通过Hash计算后,执行分配数组位置,此时就会产生hash冲突问题。在HashMap中,hash冲突采用数组+链表的方式处理,然而在ThreadLocalMap中,采用了向后递推的方式,类似于一致性Hash算法的方式。
下面再来看下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方法同样是先从当前线程中获取ThreadLocalMap实例,然后通过ThreadLocalMap.getEntry获取当前值
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);
}
这里若没有产生hash冲突,threaLocalhashCode经过一次计算后,将会直接获取到所需要的值。但是若此i存储hash冲突问题,就需要调用getEntryAfterMiss方法,查找数组中其他元素,直到找到为止
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
Entry[] tab = table;
int len = tab.length;
while (e != null) {
ThreadLocal<?> k = e.get();
if (k == key)
return e;
if (k == null)
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
FastThreadLocal机制
下面同样的方式,分析FastThreadLocal的get和set方法
public final V get() {
return get(InternalThreadLocalMap.get());
}
@SuppressWarnings("unchecked")
public final V get(InternalThreadLocalMap threadLocalMap) {
Object v = threadLocalMap.indexedVariable(index);
if (v != InternalThreadLocalMap.UNSET) {
return (V) v;
}
return initialize(threadLocalMap);
}
从无参的get方法,获取一个变量InternalThreadLocalMap,这个变量存储在FastThreadLocalThread中
public static InternalThreadLocalMap get() {
Thread thread = Thread.currentThread();
if (thread instanceof FastThreadLocalThread) {
return fastGet((FastThreadLocalThread) thread);
} else {
return slowGet();
}
}
private static InternalThreadLocalMap fastGet(FastThreadLocalThread thread) {
InternalThreadLocalMap threadLocalMap = thread.threadLocalMap();
if (threadLocalMap == null) {
thread.setThreadLocalMap(threadLocalMap = new InternalThreadLocalMap());
}
return threadLocalMap;
}
从上述中看出,FastThreadLocalThread中维持了一个变量InternalThreadLocalMap,这个map类似于Thread中的ThreadLocalMap,结合get(InternalThreadLocalMap threadLocalMap)方法,可以看出FastThreadLocal的数据存储在InternalThreadLocalMap中,查看下面看下InternalThreadLocalMap中indexedVariable方法是如何实现的
public Object indexedVariable(int index) {
Object[] lookup = indexedVariables;
return index < lookup.length? lookup[index] : UNSET;
}
此方法中可以看出InternalThreadLocaMap中也维持了一个数组,用于保存数据,区别在于直接根据传入的index来获取数据。那么这个index是如何能唯一确定一个线程的变量呢。先看下这个index的定义
private final int index;
public FastThreadLocal() {
index = InternalThreadLocalMap.nextVariableIndex();
}
可以看出,这个index在初始化时,就赋值了。
public static int nextVariableIndex() {
int index = nextIndex.getAndIncrement();
if (index < 0) {
nextIndex.decrementAndGet();
throw new IllegalStateException("too many thread-local indexed variables");
}
return index;
}
赋值方法nextVariableIndex,作为一个静态方法获取递增的nextIndex,即每创建的一个FastThreadLocal变量,将会生成一个index,在看下nextIndex是如何为了保证线程安全的
static final AtomicInteger nextIndex = new AtomicInteger();
从这个定义可以看出,产生index时,使用AtomicInteger.getAndIncrement()原子操作,通过CAS保证了线程的安全性。
总结
- ThreadLocal和FastThreadLocal在多线程访问同一变量的情况下,性能相差不多
- 在单线程访问多个变量时,性能相差较大
- 原因是由于在使用ThreadLocal时,若只有一个变量,不会频繁产生hash冲突,相对于FastThreadLocal只是多进行了一次hash算法,而此hash算法又很简单,所以不会对性能产生很大的影响
- 对于单线程访问多个ThreadLocal时,由于会产生大量的Hash冲突,不管是在get或set时,都将会有很多的冲突,这样极大的影响了ThreadLocalMap的性能
- FastThreadLocal很好的解决了这个问题,通过确定每个线程的唯一索引值,直接定位到InternalThreadLocal中的槽位,而产生唯一索引的方法,也做了线程安全的处理。