FastThreadLocal 为什么快?

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}.
  • 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.
  • 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.
  • 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}.
  • @param the type of the thread-local variable
  • @see ThreadLocal
    */
    public class FastThreadLocal {

    }
    FastThreadLocal 是一个特殊的 ThreadLocal 变体,当从线程类 FastThreadLocalThread 中访问 FastThreadLocalm时可以获得更高的访问性能。
    在这里插入图片描述

二、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 的巧妙之处。如果你不知道netty怎么使用,可以去https://www.xiaoyuani.com/看一下详细操作。

要利用 FastThreadLocal 带来的性能优势,就必须结合使用 FastThreadLocalThread 线程类或其子类,因为 FastThreadLocalThread 线程类会存储必要的状态,如果使用了非 FastThreadLocalThread 线程类则会回到常规 ThreadLocal。

Netty 提供了继承类和实现接口的线程类:

FastThreadLocalRunnable
FastThreadLocalThread

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

在这里插入图片描述

先创建 FastThreadLocalRunnable,再创建 FastThreadLocalThread,基友搭配,干活不累,一定要配合使用才“快”。

三、FastThreadLocal 实战
要使用 FastThreadLocal 就需要导入 Netty 的依赖了:

io.netty netty-all 4.1.52.Final 写一个测试小示例:

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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FastThreadLocal 是一个轻量级的线程局部变量管理库,相比于 Java 标准库中的 ThreadLocal,它在某些场景下可以提供更好的性能和内存管理。然而,FastThreadLocal 也有其缺点: 1. **依赖于第三方库**:引入 FastThreadLocal 需要额外的库支持,这可能会增加项目的复杂性和依赖管理的难度。 2. **不适用于所有环境**:虽然它可能在单线程或轻量级多线程应用中表现优秀,但在高并发或多线程竞争激烈的应用中,由于没有 Java 内置的同步机制,可能出现线程安全问题,特别是在处理并发读写时。 3. **缓存无效**:如果 FastThreadLocal 实例中的数据结构发生变化,且没有进行相应的清理或刷新操作,可能导致线程间的数据不一致。 4. **内存消耗**:虽然相比 ThreadLocal,FastThreadLocal 可能更节省内存,但过度使用也可能导致不必要的内存碎片,尤其是在每个线程都有大量 FastThreadLocal 实例的情况下。 至于性能,FastThreadLocal 在某些情况下确实可能更,因为它通常提供了更底层的实现和优化。然而,是否比 ThreadLocal 性能更高取决于具体的使用场景、实现细节以及代码的优化程度。一般而言,如果线程创建频繁或有复杂的共享状态管理需求,ThreadLocal 的同步机制可能会导致更多的开销。因此,选择 FastThreadLocal 还是 ThreadLocal 应该基于实际需求和性能测试。在决定使用哪种技术时,应该权衡它们之间的性能、复杂性和维护成本。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值