Netty源码(十四):FastThreadLocal工具类

1. 写一个程序来验证FastThreadLocal功能

public class TestFastThreadLocal {
    // FastThreadLocal初始化
    public static FastThreadLocal<Object> fastThreadLocal1 = new FastThreadLocal<Object>(){
        @Override
        protected Object initialValue() throws Exception {
            return new Object();
        }
    };

    public static void main(String[] args) {
        // 创建一个线程不断的修改fastThreadLocal1中的对象
        new Thread(()->{
            Object o = fastThreadLocal1.get();
            System.out.println(o);

            while (true){
                fastThreadLocal1.set(new Object());
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();;

        // 创建一个线程不断的获取fastThreadLocal1中的对象
        new Thread(()->{
            Object o = fastThreadLocal1.get();
            System.out.println(o);

            while (true){
                System.out.println(o==fastThreadLocal1.get());
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();;
    }
}

在这里插入图片描述

2. FastThreadLocal的创建过程

获取唯一标识
在这里插入图片描述
跟进nextVariableIndex()方法
在这里插入图片描述

3.FastThreadLocal的get()方法

FastThreadLocal的get过程和jdk的ThreadLocal是相同的
1.获取ThreadLocalMap
2.通过index获取其中的Object
3.初始化
在这里插入图片描述

3.1 跟进InternalThreadLocalMap.get()

判断当前线程是否是FastThreadLocalThread,根据情况使用不同的get方法
如果我们不是使用FastThreadLocalThread,因为中间借助了jdk的ThreadLocal,速度不一定比jdk的ThreadLocal快。
在这里插入图片描述
跟进fastGet()
在这里插入图片描述

3.2 InternalThreadLocalMap的indexedVariable()方法

相比jdk的ThreadLocal,FastThreadLocal用数组查询代替了map查询,使得查询速度更快,通过当前线程的index,得到对应的Object
在这里插入图片描述

4.FastThreadLocal的set()方法

跟进set()方法
在这里插入图片描述
本质就是将数组的index位置设置值
在这里插入图片描述

发布了275 篇原创文章 · 获赞 42 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_35688140/article/details/105562107