2017年写Netty相关文章的时候,关于Netty中FastThreadLocal.java源码解读的文章还很少。今天(2019-02-25)回头过来整理的时候,发现网上已经涌现出了许多篇介绍FastThreadLocal.java的文章,并且,已经有解读的比较详实的文章,所以本人已经不打算进一步分析源码了。此处暂且列出几篇优秀的博文供大家查阅。
下文将给出一个测试例子,用于比较ThreadLocal与FastThreadLocal的性能。
import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.concurrent.FastThreadLocalThread;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
public class FastThreadLocalTest {
public static void testThreadLocal(int threadLocalCount, int runCount, String value) {
final ThreadLocal<String>[] caches = new ThreadLocal[threadLocalCount];
final Thread mainThread = Thread.currentThread();
for (int i = 0; i < threadLocalCount; i++) {
caches[i] = new ThreadLocal();
}
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < threadLocalCount; i++) {
caches[i].set(value);
}
long start = System.nanoTime();
for (int i = 0; i < threadLocalCount; i++) {
for (int j = 0; j < runCount; j++) {
caches[i].get();
}
}
long end = System.nanoTime();
System.out.println(" thread local take[" + TimeUnit.NANOSECONDS.toMillis(end - start) +
"]ms");
LockSupport.unpark(mainThread);
}
});
t.start();
LockSupport.park(mainThread);
}
public static void testFastThreadLocal(int threadLocalCount, int runCount, String value) {
final FastThreadLocal<String>[] caches = new FastThreadLocal[threadLocalCount];
final Thread mainThread = Thread.currentThread();
for (int i = 0; i < threadLocalCount; i++) {
caches[i] = new FastThreadLocal();
}
Thread t = new FastThreadLocalThread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < threadLocalCount; i++) {
caches[i].set(value);
}
long start = System.nanoTime();
for (int i = 0; i < threadLocalCount; i++) {
for (int j = 0; j < runCount; j++) {
caches[i].get();
}
}
long end = System.nanoTime();
System.out.println("fast thread local take[" + TimeUnit.NANOSECONDS.toMillis(end - start) +
"]ms");
LockSupport.unpark(mainThread);
}
});
t.start();
LockSupport.park(mainThread);
}
@Test
public void test() {
String value = "thread local value";
testThreadLocal(1000, 1000000, value);
testFastThreadLocal(1000, 1000000, value);
}
}