FastThreadLocal 是什么鬼?吊打 ThreadLocal 的存在!!

简介: FastThreadLocal 是什么鬼?吊打 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


image.png

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


image.png


先创建 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));
    }
}

结果输出:

image.png


可以看出,在大量读写面前,写操作的效率差不多,但读操作 FastThreadLocal 比 ThreadLocal 快的不是一个数量级,简直是秒杀 ThreadLocal 的存在。


当我把 MAX 值调整到 1000 时,结果输出:


image.png


读写操作不多时,ThreadLocal 明显更胜一筹!


上面的示例是单线程测试多个 *ThreadLocal,即数组形式,另外,我也测试了多线程单个 *ThreadLocal,这时候 FastThreadLocal 效率就明显要落后于 ThreadLocal。。


最后需要说明的是,在使用完 FastThreadLocal 之后不用 remove 了,因为在 FastThreadLocalRunnable 中已经加了移除逻辑,在线程运行完时会移除全部绑定在当前线程上的所有变量。


image.png


所以,使用 FastThreadLocal 导致内存溢出的概率会不会要低于 ThreadLocal?


不一定,因为 FastThreadLocal 会产生大量的 index 常量,所谓的空间换时间,所以感觉 FastThreadLocal 内存溢出的概率更大,但好在每次使用完都会自动 remove。


四、总结

Netty 中的 FastThreadLocal 在大量频繁读写操作时效率要高于 ThreadLocal,但要注意结合 Netty 自带的线程类使用,这可能就是 Netty 为什么高性能的奥妙之一吧!


如果没有大量频繁读写操作的场景,JDK 自带的 ThreadLocal 足矣,并且性能还要优于 FastThreadLocal。


好了,今天的分享就到这里了,觉得有用,转发分享一下哦。


相关文章
|
消息中间件 安全 Java
面试官:说说SpringAOP实现原理?
面试官:说说SpringAOP实现原理?
561 3
|
Java Linux Maven
SpringBoot多环境的yml或properties配置,生产环境和开发环境分离(超详细)
SpringBoot多环境的yml或properties配置,生产环境和开发环境分离(超详细)
1177 0
|
8月前
|
Java 语音技术 内存技术
Java 实现可靠的 WAV 音频拼接:从结构解析到完整可播放的高质量合并方案
本文详解Java实现WAV音频可靠拼接的技术方案,深入剖析RIFF文件结构,动态定位data块,精准合并音频数据。解决播放异常、时长错误等问题,支持复杂结构WAV文件,确保音质一致、播放流畅,适用于TTS、语音导航等场景,提供稳定、通用、无需第三方依赖的高质量合并方案。
Java 实现可靠的 WAV 音频拼接:从结构解析到完整可播放的高质量合并方案
|
8月前
|
NoSQL IDE MongoDB
Studio 3T 2025.19 (macOS, Linux, Windows) - MongoDB 的终极 GUI、IDE 和 客户端
Studio 3T 2025.19 (macOS, Linux, Windows) - MongoDB 的终极 GUI、IDE 和 客户端
333 0
Studio 3T 2025.19 (macOS, Linux, Windows) - MongoDB 的终极 GUI、IDE 和 客户端
|
SQL 存储 数据处理
探索SQL技能提升的七个高阶使用技巧。
通过上述技巧的运用,可以使得数据库查询更为高效、安全而且易于维护。这些技巧的掌握需要在实际应用中不断地实践和反思,以不断提高数据处理的速度和安全性。
318 25
|
Java Apache Spring
Java发送Http请求(HttpClient)
Java发送Http请求(HttpClient)
13630 2
|
Java
如何将OffsetDateTime转换为字符串格式的日期
【10月更文挑战第30天】如何将OffsetDateTime转换为字符串格式的日期
545 0
|
开发框架 Java 开发者
Spring Boot中的自动装配原理
Spring Boot中的自动装配原理
3900 1
|
消息中间件 存储 负载均衡
高并发流量杀手锏:揭秘秒杀系统背后的削峰技术!
本文介绍了秒杀场景下的“削峰填谷”策略,通过消息队列缓冲用户请求,避免高并发对系统造成冲击。文中详细解释了消息队列的工作原理及如何通过预扣减库存和分布式锁确保数据一致性,同时还提出了合理的消息队列配置、高可用性及数据库负载均衡等最佳实践。通过这些技术手段,可有效提升系统的稳定性和用户体验。
1108 8
高并发流量杀手锏:揭秘秒杀系统背后的削峰技术!
|
SQL 关系型数据库 MySQL
MyBatis-plus执行自定义SQL
MyBatis-plus执行自定义SQL
812 0