netty源码阅读之性能优化工具类之FastThreadLocal的使用

先说明FastThreadLocal使用的效果。

1、比jdk原生的ThreadLocal的快

2、不同线程之间能保证线程安全

这是我们的用户代码:

public class FastThreadLocalTest {
    private static FastThreadLocal<Object> threadLocal = new FastThreadLocal<Object>() {
        @Override
        protected Object initialValue() {
            return new Object();
        }

        @Override
        protected void onRemoval(Object value) throws Exception {
            System.out.println("onRemoval");
        }
    };


    public static void main(String[] args) {
        new Thread(() -> {
            Object object = threadLocal.get();
            // .... do with object
            System.out.println(object);
            threadLocal.set(new Object());

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

        new Thread(() -> {
            Object object = threadLocal.get();
            // ... do with object
            System.out.println(object);
            while (true) {
                System.out.println(threadLocal.get() == object);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

我们创建了一个FastThreadLocal,然后在两个不同的线程里面做get,得到两个不同的对象。

所以得出的结果是打印了两个不同的对象。

后面及时在一个线程里面修改threadLocal(也就是不停地set new Object对象),另外一个线程get到的对象还是和之前的相同。

所以证明了不同的线程,get set的时候不会有影响。

猜你喜欢

转载自blog.csdn.net/fst438060684/article/details/82956320