当前位置:网站首页>FastThreadLocal 是什么鬼?吊打 ThreadLocal 的存在!!
FastThreadLocal 是什么鬼?吊打 ThreadLocal 的存在!!
2020-11-06 21:09:00 【Java技术栈】
ThreadLocal 大家都知道是线程本地变量,今天栈长再介绍一个神器:FastThreadLocal,从字面上看就是:Fast + ThreadLocal,一个快的 ThreadLocal?这到底是什么鬼呢?
一、FastThreadLocal 简介
FastThreadLocal 并不是 JDK 自带的,而是在 Netty 中造的一个轮子,Netty 为什么要重复造轮子呢?
来看下它源码中的注释定义:
/**
* A special variant of {@link ThreadLocal} that yields higher access performance when accessed from a
* {@link FastThreadLocalThread}.
* <p>
* Internally, a {@link FastThreadLocal} uses a constant index in an array, instead of using hash code and hash table,
* to look for a variable. Although seemingly very subtle, it yields slight performance advantage over using a hash
* table, and it is useful when accessed frequently.
* </p><p>
* To take advantage of this thread-local variable, your thread must be a {@link FastThreadLocalThread} or its subtype.
* By default, all threads created by {@link DefaultThreadFactory} are {@link FastThreadLocalThread} due to this reason.
* </p><p>
* Note that the fast path is only possible on threads that extend {@link FastThreadLocalThread}, because it requires
* a special field to store the necessary state. An access by any other kind of thread falls back to a regular
* {@link ThreadLocal}.
* </p>
*
* @param <V> the type of the thread-local variable
* @see ThreadLocal
*/
public class FastThreadLocal<V> {
...
}
FastThreadLocal 是一个特殊的 ThreadLocal 变体,当从线程类 FastThreadLocalThread 中访问 FastThreadLocalm时可以获得更高的访问性能。如果你还不知道什么是 ThreadLocal,可以关注公众号Java技术栈阅读我之前分享的文章。
二、FastThreadLocal 为什么快?
在 FastThreadLocal 内部,使用了索引常量代替了 Hash Code 和哈希表,源代码如下:
private final int index;
public FastThreadLocal() {
index = InternalThreadLocalMap.nextVariableIndex();
}
public static int nextVariableIndex() {
int index = nextIndex.getAndIncrement();
if (index < 0) {
nextIndex.decrementAndGet();
throw new IllegalStateException("too many thread-local indexed variables");
}
return index;
}
FastThreadLocal 内部维护了一个索引常量 index,该常量在每次创建 FastThreadLocal 中都会自动+1,从而保证了下标的不重复性。
这要做虽然会产生大量的 index,但避免了在 ThreadLocal 中计算索引下标位置以及处理 hash 冲突带来的损耗,所以在操作数组时使用固定下标要比使用计算哈希下标有一定的性能优势,特别是在频繁使用时会非常显著,用空间换时间,这就是高性能 Netty 的巧妙之处。
要利用 FastThreadLocal 带来的性能优势,就必须结合使用 FastThreadLocalThread 线程类或其子类,因为 FastThreadLocalThread 线程类会存储必要的状态,如果使用了非 FastThreadLocalThread 线程类则会回到常规 ThreadLocal。
Netty 提供了继承类和实现接口的线程类:
- FastThreadLocalRunnable
- FastThreadLocalThread

Netty 也提供了 DefaultThreadFactory 工厂类,所有由 DefaultThreadFactory 工厂类创建的线程默认就是 FastThreadLocalThread 类型,来看下它的创建过程:

先创建 FastThreadLocalRunnable,再创建 FastThreadLocalThread,基友搭配,干活不累,一定要配合使用才“快”。
三、FastThreadLocal 实战
要使用 FastThreadLocal 就需要导入 Netty 的依赖了:
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.52.Final</version>
</dependency>
写一个测试小示例:
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.FastThreadLocal;
public class FastThreadLocalTest {
public static final int MAX = 100000;
public static void main(String[] args) {
new Thread(() -> threadLocal()).start();
new Thread(() -> fastThreadLocal()).start();
}
private static void fastThreadLocal() {
long start = System.currentTimeMillis();
DefaultThreadFactory defaultThreadFactory = new DefaultThreadFactory(FastThreadLocalTest.class);
FastThreadLocal<String>[] fastThreadLocal = new FastThreadLocal[MAX];
for (int i = 0; i < MAX; i++) {
fastThreadLocal[i] = new FastThreadLocal<>();
}
Thread thread = defaultThreadFactory.newThread(() -> {
for (int i = 0; i < MAX; i++) {
fastThreadLocal[i].set("java: " + i);
}
System.out.println("fastThreadLocal set: " + (System.currentTimeMillis() - start));
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
fastThreadLocal[i].get();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("fastThreadLocal total: " + (System.currentTimeMillis() - start));
}
private static void threadLocal() {
long start = System.currentTimeMillis();
ThreadLocal<String>[] threadLocals = new ThreadLocal[MAX];
for (int i = 0; i < MAX; i++) {
threadLocals[i] = new ThreadLocal<>();
}
Thread thread = new Thread(() -> {
for (int i = 0; i < MAX; i++) {
threadLocals[i].set("java: " + i);
}
System.out.println("threadLocal set: " + (System.currentTimeMillis() - start));
for (int i = 0; i < MAX; i++) {
for (int j = 0; j < MAX; j++) {
threadLocals[i].get();
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("threadLocal total: " + (System.currentTimeMillis() - start));
}
}
结果输出:

可以看出,在大量读写面前,写操作的效率差不多,但读操作 FastThreadLocal 比 ThreadLocal 快的不是一个数量级,简直是秒杀 ThreadLocal 的存在。
当我把 MAX 值调整到 1000 时,结果输出:

读写操作不多时,ThreadLocal 明显更胜一筹!
上面的示例是单线程测试多个 *ThreadLocal,即数组形式,另外,我也测试了多线程单个 *ThreadLocal,这时候 FastThreadLocal 效率就明显要落后于 ThreadLocal。。
最后需要说明的是,在使用完 FastThreadLocal 之后不用 remove 了,因为在 FastThreadLocalRunnable 中已经加了移除逻辑,在线程运行完时会移除全部绑定在当前线程上的所有变量。

所以,使用 FastThreadLocal 导致内存溢出的概率会不会要低于 ThreadLocal?
不一定,因为 FastThreadLocal 会产生大量的 index 常量,所谓的空间换时间,所以感觉 FastThreadLocal 内存溢出的概率更大,但好在每次使用完都会自动 remove。
四、总结
Netty 中的 FastThreadLocal 在大量频繁读写操作时效率要高于 ThreadLocal,但要注意结合 Netty 自带的线程类使用,这可能就是 Netty 为什么高性能的奥妙之一吧!
如果没有大量频繁读写操作的场景,JDK 自带的 ThreadLocal 足矣,并且性能还要优于 FastThreadLocal。
好了,今天的分享就到这里了,觉得有用,转发分享一下哦。
最后,Java 系列教程还会继续更新,关注Java技术栈公众号第一时间推送,还可以在公众号菜单中获取历史 Java 教程,都是干货。
版权申明:本文系公众号 "Java技术栈" 原创,原创实属不易,转载、引用本文内容请注明出处,禁止抄袭、洗稿,请自重,尊重他人劳动成果和知识产权。
近期热文推荐:
1.Java 15 正式发布, 14 个新特性,刷新你的认知!!
2.终于靠开源项目弄到 IntelliJ IDEA 激活码了,真香!
3.我用 Java 8 写了一段逻辑,同事直呼看不懂,你试试看。。
觉得不错,别忘了随手点赞+转发哦!
版权声明
本文为[Java技术栈]所创,转载请带上原文链接,感谢
https://my.oschina.net/javaroad/blog/4702236
边栏推荐
- Introduction to X Window System
- Cglib 如何实现多重代理?
- High availability cluster deployment of jumpserver: (6) deployment of SSH agent module Koko and implementation of system service management
- NLP model Bert: from introduction to mastery (2)
- 百万年薪,国内工作6年的前辈想和你分享这四点
- [C / C + + 1] clion configuration and running C language
- It's so embarrassing, fans broke ten thousand, used for a year!
- Let the front-end siege division develop independently from the back-end: Mock.js
- Interface pressure test: installation, use and instruction of siege pressure test
- Save the file directly to Google drive and download it back ten times faster
猜你喜欢

vue-codemirror基本用法:实现搜索功能、代码折叠功能、获取编辑器值及时验证

Free patent download tutorial (HowNet, Espacenet)

零基础打造一款属于自己的网页搜索引擎

Three Python tips for reading, creating and running multiple files

A brief history of neural networks

每个前端工程师都应该懂的前端性能优化总结:

教你轻松搞懂vue-codemirror的基本用法:主要实现代码编辑、验证提示、代码格式化

Cglib 如何实现多重代理?

一篇文章带你了解CSS对齐方式

带你学习ES5中新增的方法
随机推荐
Network security engineer Demo: the original * * is to get your computer administrator rights! 【***】
前端工程师需要懂的前端面试题(c s s方面)总结(二)
小程序入门到精通(二):了解小程序开发4个重要文件
How to use Python 2.7 after installing anaconda3?
理解格式化原理
Thoughts on interview of Ali CCO project team
一篇文章带你了解CSS 分页实例
[event center azure event hub] interpretation of error information found in event hub logs
前端都应懂的入门基础-github基础
Let the front-end siege division develop independently from the back-end: Mock.js
H5 makes its own video player (JS Part 2)
A brief history of neural networks
ES6学习笔记(四):教你轻松搞懂ES6的新增语法
High availability cluster deployment of jumpserver: (6) deployment of SSH agent module Koko and implementation of system service management
ES6 essence:
How to demote domain controllers and later in Windows Server 2012
The choice of enterprise database is usually decided by the system architect - the newstack
What is the side effect free method? How to name it? - Mario
Nodejs crawler captures ancient books and records, a total of 16000 pages, experience summary and project sharing
Python3 e-learning case 4: writing web proxy