欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ThreadLocal工作原理及用法案例

程序员文章站 2022-06-19 16:44:39
threadlocal是什么threadlocal是线程thread中属性threadlocals即threadlocal.threadlocalmap的管理者,threadlocal用于给每个线程操...

threadlocal是什么

threadlocal是线程thread中属性threadlocals即threadlocal.threadlocalmap的管理者,threadlocal用于给每个线程操作自己线程的本地变量,通过线程私有从而保证线程安全性。

threadlocal原理

get()方法来说,线程的本地变量是存放在线程实例的属性threadlocalmap上的,threadlocalmap本质上就是一个hashmap,threadlocal只是一个管理者,当我们的线程需要拿到自己的本地变量时,我们直接调用threadlocal去get本地变量即可。
因为get()方法底层会先获取到当前线程,然后通过当前线程拿到他的属性值threadlocalmap,如果threadlocalmap为空,则会调用threadlocal的初始化方法拿到初始值返回,如果不为空,则会拿该threadlocal作为key去获取该线程下的threadlocalmap里对应的value值。

threadlocal内存泄漏问题

线程的属性值threadlocalmap中使用的 key 为 threadlocal 的弱引用,而value是强引用。所以,如果threadlocal没有被外部强引用的情况下,在垃圾回收的时候,key 会被清理掉,而value 不会被清理掉。这样的话,threadlocalmap 中就会出现 key 为 null 的 entry。假如我们不做任何措施的话,value 永远无法被 gc 回收,这个时候就可能会产生内存泄露。
因此针对这种情况,我们有两种原则:

  • threadlocal申明为private static final。jdk建议threadlocal定义为private static,这样threadlocal的弱引用问题则不存在了。
    • private与final 尽可能不让他人修改变更引用。
    • static 表示为类属性,只有在程序结束才会被回收。
  • threadlocal使用后务必调用remove方法。
    • 最简单有效的方法是使用后将其移除。

关于inheritablethreadlocal

inheritablethreadlocal类是threadlocal类的子类。threadlocal中每个线程拥有它自己的值,与threadlocal不同的是,inheritablethreadlocal允许一个线程以及该线程创建的所有子线程都可以访问它保存的值。

代码示例

threadlocal使用

public class threadlocaltest {

    //第一种初始化方式
    /**
     * 声明为static是让threadlocal实例随着程序的结束才结束,这样才不会让gc回收了
     * 声明为final是让threadlocal实例引用不会被替换,这样子也不会因为被替换导致被gc回收
     * 这两个声明都是为了避免作为key的threadlocal对象没有外部强引用而导致被gc回收,从而导致内存泄漏的问题,因为threadlocalmap<threadlocal, object>中的threadlocal
     * 对象作为key是弱引用,会被gc回收。
     */
    private static final threadlocal<string> threadlocalstr = threadlocal.withinitial(() -> "fresh");

    private static atomicinteger intgen = new atomicinteger(0);
    //第二种初始化方式
    private static final threadlocal<integer> threadlocalint = new threadlocal<integer>() {
        @override
        public integer initialvalue() {
            return intgen.incrementandget();
        }
    };

    public static void main(string[] args) throws interruptedexception {
        arraylist<thread> threads = new arraylist<>();
        for (int i = 0; i < 2; i++) {
            thread t = new thread(() -> {
                try {
                    system.out.println(thread.currentthread().getname() + "   " + threadlocalint.get());
                    system.out.println(thread.currentthread().getname() + "   " + threadlocalstr.get());
                    timeunit.seconds.sleep(5);
                    threadlocalstr.set("bojack horseman" + threadlocalint.get());
                    system.out.println(thread.currentthread().getname() + "   " + threadlocalint.get());
                    system.out.println(thread.currentthread().getname() + "   " + threadlocalstr.get());
                } catch (interruptedexception e) {
                    e.printstacktrace();
                } finally {
                    threadlocalint.remove();
                    threadlocalstr.remove();
                }
            });
            t.start();
            threads.add(t);
        }
        timeunit.seconds.sleep(2);
        system.out.println(threads);
        system.out.println(threadlocalstr);
        system.out.println(threadlocalint);
    }
    /**
     * thread-0   1
     * thread-1   2
     * thread-0   fresh
     * thread-1   fresh
     * [thread[thread-0,5,main], thread[thread-1,5,main]]
     * java.lang.threadlocal$suppliedthreadlocal@1ef7fe8e
     * cn.vv.schedule.test.threadlocaltest$1@6f79caec
     * thread-1   2
     * thread-1   bojack horseman2
     * thread-0   1
     * thread-0   bojack horseman1
     */

}

inheritablethreadlocal使用

public class inheritablethreadlocaltest {

    //第一种初始化方式
    private static final inheritablethreadlocal<string> threadlocalstr = new inheritablethreadlocal<string>() {
        @override
        public string initialvalue() {
            return "fresh";
        }
    };
    private static atomicinteger intgen = new atomicinteger(0);
    //第二种初始化方式
    private static final threadlocal<integer> threadlocalint = new threadlocal<integer>() {
        @override
        public integer initialvalue() {
            return intgen.incrementandget();
        }
    };

    public static void main(string[] args) throws interruptedexception {
        //如果是inheritablethreadlocal,则父线程创建的所有子线程都会复制一份父线程的线程变量,而不是去初始化一份线程变量
        threadlocalstr.set("main");
        arraylist<thread> threads = new arraylist<>();
        for (int i = 0; i < 2; i++) {
            thread t = new thread(() -> {
                try {
                    system.out.println(thread.currentthread().getname() + "   " + threadlocalint.get());
                    system.out.println(thread.currentthread().getname() + "   " + threadlocalstr.get());
                    timeunit.seconds.sleep(5);
                    //子线程可以*地改变自己的本地变量
                    threadlocalstr.set("bojack horseman" + threadlocalint.get());
                    system.out.println(thread.currentthread().getname() + "   " + threadlocalint.get());
                    system.out.println(thread.currentthread().getname() + "   " + threadlocalstr.get());
                } catch (interruptedexception e) {
                    e.printstacktrace();
                } finally {
                    threadlocalint.remove();
                    threadlocalstr.remove();
                }
            });
            t.start();
            threads.add(t);
        }
        timeunit.seconds.sleep(2);
        system.out.println(thread.currentthread().getname() + "   " + threadlocalstr.get());
    }
    /**
     * thread-0   2
     * thread-1   1
     * thread-0   main
     * thread-1   main
     * main   main
     * thread-0   2
     * thread-0   bojack horseman2
     * thread-1   1
     * thread-1   bojack horseman1
     */

}

参考

threadlocal理解及应用