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

开发 前端
ThreadLocal 大家都知道是线程本地变量,今天栈长再介绍一个神器:FastThreadLocal,从字面上看就是:Fast + ThreadLocal,一个快的 ThreadLocal?这到底是什么鬼呢?

 [[350411]]

ThreadLocal 大家都知道是线程本地变量,今天栈长再介绍一个神器:FastThreadLocal,从字面上看就是:Fast + ThreadLocal,一个快的 ThreadLocal?这到底是什么鬼呢?

一、FastThreadLocal 简介

FastThreadLocal 并不是 JDK 自带的,而是在 Netty 中造的一个轮子,Netty 为什么要重复造轮子呢?

来看下它源码中的注释定义:

  1. /** 
  2.  * A special variant of {@link ThreadLocal} that yields higher access performance when accessed from a 
  3.  * {@link FastThreadLocalThread}. 
  4.  * <p> 
  5.  * Internally, a {@link FastThreadLocal} uses a constant index in an array, instead of using hash code and hash table
  6.  * to look for a variable.  Although seemingly very subtle, it yields slight performance advantage over using a hash 
  7.  * tableand it is useful when accessed frequently. 
  8.  * </p><p> 
  9.  * To take advantage of this thread-local variable, your thread must be a {@link FastThreadLocalThread} or its subtype. 
  10.  * By defaultall threads created by {@link DefaultThreadFactory} are {@link FastThreadLocalThread} due to this reason. 
  11.  * </p><p> 
  12.  * Note that the fast path is only possible on threads that extend {@link FastThreadLocalThread}, because it requires 
  13.  * a special field to store the necessary state.  An access by any other kind of thread falls back to a regular 
  14.  * {@link ThreadLocal}. 
  15.  * </p> 
  16.  * 
  17.  * @param <V> the type of the thread-local variable 
  18.  * @see ThreadLocal 
  19.  */ 
  20. public class FastThreadLocal<V> { 
  21.  ... 

 

FastThreadLocal 是一个特殊的 ThreadLocal 变体,当从线程类 FastThreadLocalThread 中访问 FastThreadLocalm时可以获得更高的访问性能。如果你还不知道什么是ThreadLocal,可以关注公众号Java技术栈阅读我之前分享的文章。

二、FastThreadLocal 为什么快?

在 FastThreadLocal 内部,使用了索引常量代替了 Hash Code 和哈希表,源代码如下:

  1. private final int index
  2.  
  3. public FastThreadLocal() { 
  4.     index = InternalThreadLocalMap.nextVariableIndex(); 
  1. public static int nextVariableIndex() { 
  2.     int index = nextIndex.getAndIncrement(); 
  3.     if (index < 0) { 
  4.         nextIndex.decrementAndGet(); 
  5.         throw new IllegalStateException("too many thread-local indexed variables"); 
  6.     } 
  7.     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 的依赖了:

  1. <dependency> 
  2.     <groupId>io.netty</groupId> 
  3.     <artifactId>netty-all</artifactId> 
  4.     <version>4.1.52.Final</version> 
  5. </dependency> 

写一个测试小示例:

  1. import io.netty.util.concurrent.DefaultThreadFactory; 
  2. import io.netty.util.concurrent.FastThreadLocal; 
  3.  
  4. public class FastThreadLocalTest { 
  5.  
  6.     public static final int MAX = 100000; 
  7.  
  8.     public static void main(String[] args) { 
  9.         new Thread(() -> threadLocal()).start(); 
  10.         new Thread(() -> fastThreadLocal()).start(); 
  11.     } 
  12.  
  13.     private static void fastThreadLocal() { 
  14.         long start = System.currentTimeMillis(); 
  15.         DefaultThreadFactory defaultThreadFactory = new DefaultThreadFactory(FastThreadLocalTest.class); 
  16.  
  17.         FastThreadLocal<String>[] fastThreadLocal = new FastThreadLocal[MAX]; 
  18.  
  19.         for (int i = 0; i < MAX; i++) { 
  20.             fastThreadLocal[i] = new FastThreadLocal<>(); 
  21.         } 
  22.  
  23.         Thread thread = defaultThreadFactory.newThread(() -> { 
  24.             for (int i = 0; i < MAX; i++) { 
  25.                 fastThreadLocal[i].set("java: " + i); 
  26.             } 
  27.  
  28.             System.out.println("fastThreadLocal set: " + (System.currentTimeMillis() - start)); 
  29.  
  30.             for (int i = 0; i < MAX; i++) { 
  31.                 for (int j = 0; j < MAX; j++) { 
  32.                     fastThreadLocal[i].get(); 
  33.                 } 
  34.             } 
  35.         }); 
  36.         thread.start(); 
  37.         try { 
  38.             thread.join(); 
  39.         } catch (InterruptedException e) { 
  40.             e.printStackTrace(); 
  41.         } 
  42.  
  43.         System.out.println("fastThreadLocal total: " + (System.currentTimeMillis() - start)); 
  44.     } 
  45.  
  46.     private static void threadLocal() { 
  47.         long start = System.currentTimeMillis(); 
  48.         ThreadLocal<String>[] threadLocals = new ThreadLocal[MAX]; 
  49.  
  50.         for (int i = 0; i < MAX; i++) { 
  51.             threadLocals[i] = new ThreadLocal<>(); 
  52.         } 
  53.  
  54.         Thread thread = new Thread(() -> { 
  55.             for (int i = 0; i < MAX; i++) { 
  56.                 threadLocals[i].set("java: " + i); 
  57.             } 
  58.  
  59.             System.out.println("threadLocal set: " + (System.currentTimeMillis() - start)); 
  60.  
  61.             for (int i = 0; i < MAX; i++) { 
  62.                 for (int j = 0; j < MAX; j++) { 
  63.                     threadLocals[i].get(); 
  64.                 } 
  65.             } 
  66.         }); 
  67.         thread.start(); 
  68.         try { 
  69.             thread.join(); 
  70.         } catch (InterruptedException e) { 
  71.             e.printStackTrace(); 
  72.         } 
  73.  
  74.         System.out.println("threadLocal total: " + (System.currentTimeMillis() - start)); 
  75.     } 
  76.  

结果输出:

 

可以看出,在大量读写面前,写操作的效率差不多,但读操作 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技术栈
相关推荐

2015-11-12 10:03:34

前端H5web

2021-11-10 12:13:02

HostonlyCookie浏览器

2017-04-03 15:35:13

知识体系架构

2020-09-27 06:53:57

MavenCDNwrapper

2021-09-13 15:17:52

FastThreadL源码Java

2019-10-30 10:13:15

区块链技术支付宝

2021-07-06 10:17:07

Python LaunLinuxWindows

2015-03-17 10:13:52

HTML5什么鬼

2021-10-11 08:58:34

Goroutine操作系统

2015-09-29 09:47:14

2022-01-12 12:35:36

Linuxworkqueue工作队列

2019-01-07 12:40:19

2021-01-07 05:22:47

MySQL字段存储

2022-09-07 08:41:57

SpringIstio分布式

2022-05-11 08:53:13

MySQL锁机制

2015-09-22 09:25:16

RTORPO灾备技术

2019-01-17 14:35:01

2016-10-21 09:58:19

WindowsKMSOEM系统

2017-09-13 11:02:17

2015-07-16 10:49:31

虚拟化容器技术
点赞
收藏

51CTO技术栈公众号