Netty中FastThreadLocal的实现原理

顾名思义,Netty中的FastThreadLocal要比JDK中的ThreadLocal更快,那FastThreadLocal是怎么做到的呢?

FastThreadLocal的使用

FastThreadLocal的使用方法和ThreadLocal基本一致,但有一点必须注意的是,FastThreadLocal必须在FastThreadLocalThread中才能体现出“Fast”的优势,在普通Thread中会退化回ThreadLocal。

import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.concurrent.FastThreadLocalThread;

public class FastThreadLocalTest {
    private static FastThreadLocal<String> fastThreadLocal = new FastThreadLocal<>();
    public static void main(String[] args) {
        fastThreadLocal.set("Main Thread");
        new FastThreadLocalThread(() -> {
            fastThreadLocal.set("Thread 1");
            System.out.println("Thread 1 => " + fastThreadLocal.get());
        }).start();
        new FastThreadLocalThread(() -> {
            fastThreadLocal.set("Thread 2");
            System.out.println("Thread 2 => " + fastThreadLocal.get());
        }).start();
        System.out.println("Main Thread => " + fastThreadLocal.get());
    }
}

程序输出:

Thread 1 => Thread 1
Main Thread => Main Thread
Thread 2 => Thread 2

Process finished with exit code 0

FastThreadLocal的原理

ThreadLocal中通过一个Map来维护每一个线程中ThreadLocal到Object的映射,这个Map使用了线性探测法来解决哈希冲突,在最坏情况下会有O(n)的复杂度,而且计算哈希码的过程本身也需要耗时。

FastThreadLocal通过空间换时间的方式解决了上述问题。每一个FastThreadLocal都有一个全局唯一的index,该index唯一确定了FastThreadLocal在每一个线程中的Object数组中的下标,因此,可以在O(1)时间内进行get和set操作。但其缺点是浪费空间,例如,某个FastThreadLocal的index很大,而某个线程只使用了此FastThreadLocal,那该线程也必须开辟至少index的数组大小才行。

下面我们来看一下源码。

首先,我们看一下FastThreadLocalThread中相关的字段。

/**
 * A special {@link Thread} that provides fast access to {@link FastThreadLocal} variables.
 */
public class FastThreadLocalThread extends Thread {
    ...
    private InternalThreadLocalMap threadLocalMap;
    ...
}

由注释也可知,FastThreadLocalThread提供了一个对FastThreadLocal变量的快速访问,其核心字段是InternalThreadLocalMap类型的变量threadLocalMap。下面我们看一下InternalThreadLocalMap的数据结构。

InternalThreadLocalMap继承自UnpaddedInternalThreadLocalMap:

class UnpaddedInternalThreadLocalMap {

    static final ThreadLocal<InternalThreadLocalMap> slowThreadLocalMap = new ThreadLocal<InternalThreadLocalMap>();
    static final AtomicInteger nextIndex = new AtomicInteger();

    /** Used by {@link FastThreadLocal} */
    Object[] indexedVariables;
    ...
}

可见其也是用数组存放了相关变量,继续看InternalThreadLocalMap。先看get方法:

    public static InternalThreadLocalMap get() {
        Thread thread = Thread.currentThread();
        if (thread instanceof FastThreadLocalThread) {
            return fastGet((FastThreadLocalThread) thread);
        } else {
            return slowGet();
        }
    }

可见,如果线程类型是FastThreadLocalThread,则使用fastGet方法,否则则用slowGet方法。需要注意的是,方法的返回值是InternalThreadLocalMap,而非具体存放的元素值。下面是fastGet和slowGet的源码:

    private static InternalThreadLocalMap fastGet(FastThreadLocalThread thread) {
        InternalThreadLocalMap threadLocalMap = thread.threadLocalMap();
        if (threadLocalMap == null) {
            thread.setThreadLocalMap(threadLocalMap = new InternalThreadLocalMap());
        }
        return threadLocalMap;
    }

    private static InternalThreadLocalMap slowGet() {
        ThreadLocal<InternalThreadLocalMap> slowThreadLocalMap = UnpaddedInternalThreadLocalMap.slowThreadLocalMap;
        InternalThreadLocalMap ret = slowThreadLocalMap.get();
        if (ret == null) {
            ret = new InternalThreadLocalMap();
            slowThreadLocalMap.set(ret);
        }
        return ret;
    }

下面我们看一下FastThreadLocal的get方法:

    /**
     * Returns the current value for the current thread
     */
    @SuppressWarnings("unchecked")
    public final V get() {
        InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.get();
        Object v = threadLocalMap.indexedVariable(index);
        if (v != InternalThreadLocalMap.UNSET) {
            return (V) v;
        }

        return initialize(threadLocalMap);
    }

不难看出,FastThreadLocal直接使用index从当前线程的threadLocalMap中取值。

关于set相关的内容和其它一些琐碎细节,读者若有兴趣可自行探索,只要理解了前文中所说的FastThreadLocal的设计理念,读懂源码将没什么困难。记住,源码之前,了无秘密。


每日学习笔记,写于2020-05-04 星期一

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。