当前位置: 移动技术网 > IT编程>开发语言>Java > 面试官:ThreadLocal的应用场景和注意事项有哪些?

面试官:ThreadLocal的应用场景和注意事项有哪些?

2020年04月05日  | 移动技术网IT编程  | 我要评论

前言

threadlocal主要有如下2个作用

  1. 保证线程安全
  2. 在线程级别传递变量

保证线程安全

最近一个小伙伴把项目中封装的日期工具类用在多线程环境下居然出了问题,来看看怎么回事吧

日期转换的一个工具类

public class dateutil {

    private static final simpledateformat sdf = 
            new simpledateformat("yyyy-mm-dd hh:mm:ss");

    public static date parse(string datestr) {
        date date = null;
        try {
            date = sdf.parse(datestr);
        } catch (parseexception e) {
            e.printstacktrace();
        }
        return date;
    }
}

然后将这个工具类用在多线程环境下

public static void main(string[] args) {

    executorservice service = executors.newfixedthreadpool(20);

    for (int i = 0; i < 20; i++) {
        service.execute(()->{
            system.out.println(dateutil.parse("2019-06-01 16:34:30"));
        });
    }
    service.shutdown();
}

结果报异常了,因为部分线程获取的时间不对在这里插入图片描述
这个异常就不从源码的角度分析了,写一个小demo,理解了这个小demo,就理解了原因

一个将数字加10的工具类

public class numutil {

    public static int addnum = 0;

    public static int add10(int num) {
        addnum = num;
        try {
            timeunit.seconds.sleep(1);
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        return addnum + 10;
    }
}
public static void main(string[] args) {

	executorservice service = executors.newfixedthreadpool(20);

	for (int i = 0; i < 20; i++) {
		int num = i;
		service.execute(()->{
			system.out.println(num + " " +  numutil.add10(num));
		});
	}
	service.shutdown();
}

然后代码的一部分输出为

0 28
3 28
7 28
11 28
15 28

什么鬼,不是加10么,怎么都输出了28?这主要是因为线程切换的原因,线程陆续将addnum值设置为0 ,3,7但是都没有执行完(没有执行到return addnum+10这一步)就被切换了,当其中一个线程将addnum值设置为18时,线程陆续开始执行addnum+10这一步,结果都输出了28。simpledateformat的原因和这个类似,那么我们如何解决这个问题呢?

解决方案

解决方案1:每次来都new新的,空间浪费比较大

public class dateutil {

    public static date parse(string datestr) {
        simpledateformat sdf =
                new simpledateformat("yyyy-mm-dd hh:mm:ss");
        date date = null;
        try {
            date = sdf.parse(datestr);
        } catch (parseexception e) {
            e.printstacktrace();
        }
        return date;
    }
}

解决方案2:方法用synchronized修饰,并发上不来

public class dateutil {

    private static final simpledateformat sdf =
            new simpledateformat("yyyy-mm-dd hh:mm:ss");

    public static synchronized date parse(string datestr) {
        date date = null;
        try {
            date = sdf.parse(datestr);
        } catch (parseexception e) {
            e.printstacktrace();
        }
        return date;
    }
}

解决方案3:用jdk1.8中的日期格式类dateformatter,datetimeformatter

public class dateutil {

    private static datetimeformatter formatter = 
            datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss");

    public static localdatetime parse(string datestr) {
        return localdatetime.parse(datestr, formatter);
    }
}

解决方案4:用threadlocal,一个线程一个simpledateformat对象

public class dateutil {

    private static threadlocal<dateformat> threadlocal = threadlocal.withinitial(
            ()-> new simpledateformat("yyyy-mm-dd hh:mm:ss"));

    public static date parse(string datestr) {
        date date = null;
        try {
            date = threadlocal.get().parse(datestr);
        } catch (parseexception e) {
            e.printstacktrace();
        }
        return date;
    }
}

上面的加10的工具类可以改成如下形式(主要为了演示threadlocal的使用)

public class numutil {

    private static threadlocal<integer> addnumthreadlocal = new threadlocal<>();

    public static int add10(int num) {
        addnumthreadlocal.set(num);
        try {
            timeunit.seconds.sleep(1);
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        return addnumthreadlocal.get() + 10;
    }
}

现在2个工具类都能正常使用了,这是为啥呢?

原理分析

当多个线程同时读写同一共享变量时存在并发问题,如果不共享不就没有并发问题了,一个线程存一个自己的变量,类比原来好几个人玩同一个球,现在一个人一个球,就没有问题了,如何把变量存在线程上呢?其实thread类内部已经有一个map容器用来存变量了。它的大概结构如下所示

在这里插入图片描述
threadlocalmap是一个map,key是threadlocal,value是object

映射到源码就是如下所示:
threadlocalmap是threadlocal的一个静态内部类

public class thread implements runnable {
    threadlocal.threadlocalmap threadlocals = null;
}

往threadlocalmap里面放值

// threadlocal类里面的方法,将源码整合了一下
public void set(t value) {
    thread t = thread.currentthread();
    threadlocalmap map = t.threadlocals;
    if (map != null)
        map.set(this, value);
    else
		t.threadlocals = new threadlocalmap(this, firstvalue);
}

从threadlocalmap里面取值

// threadlocal类里面的方法,将源码整合了一下
public t get() {
	thread t = thread.currentthread();
	threadlocalmap map = t.threadlocals;
	if (map != null) {
		threadlocalmap.entry e = map.getentry(this);
		if (e != null) {
			@suppresswarnings("unchecked")
			t result = (t)e.value;
			return result;
		}
	}
	return setinitialvalue();
}

从threadlocalmap里面删除值

// threadlocal类里面的方法,将源码整合了一下
public void remove() {
	threadlocalmap m = thread.currentthread().threadlocals;
	if (m != null)
		m.remove(this);
}

执行如下代码

public class infoutil {

    private static threadlocal<string> nameinfo = new threadlocal<>();
    private static threadlocal<integer> ageinfo = new threadlocal<>();

    public static void setinfo(string name, integer age) {
        nameinfo.set(name);
        ageinfo.set(age);
    }

    public static string getname() {
        return nameinfo.get();
    }

    public static void main(string[] args) {
        new thread(() -> {
            infoutil.setinfo("张三", 10);
            // 张三
            system.out.println(infoutil.getname());
        }, "thread1").start();
        new thread(() -> {
            infoutil.setinfo("李四", 20);
            // 李四
            system.out.println(infoutil.getname());
        }, "thread2").start();
    }
}

变量的结构如下图
在这里插入图片描述

在线程级别传递变量

假设有如下一个场景,method1()调用method2(),method2()调用method3(),method3()调用method4(),method1()生成了一个变量想在method4()中使用,有如下2种解决办法

  1. method 2 3 4的参数列表上都写上method4想要的变量
  2. method 1 往threadlocal中put一个值,method4从threadlocal中get出来

哪种实现方式比较优雅呢?相信我不说你也能明白了

我在生产环境中一般是这样用的,如果一个请求在系统中的处理流程比较长,可以对请求的日志打一个相同的前缀,这样比较方便处理问题

这个前缀的生成和移除可以配置在拦截器中,切面中,当然也可以在一个方法的前后

public class main {

    public static final threadlocal<string> spanid =
            threadlocal.withinitial(() -> uuid.randomuuid().tostring());

    public static void start() {
        spanid.set(uuid.randomuuid().tostring());
        // 方法调用过程中可以在日志中打印spanid表明一个请求的执行链路
        spanid.remove();
    }
}

当然spring cloud已经有现成的链路追踪组件了。

threadlocal使用注意事项

threadlocal如果使用不当会造成如下问题

  1. 脏数据
  2. 内存泄露

脏数据

线程复用会造成脏数据。由于线程池会复用thread对象,因此thread类的成员变量threadlocals也会被复用。如果在线程的run()方法中不显示调用remove()清理与线程相关的threadlocal信息,并且下一个线程不调用set()设置初始值,就可能get()到上个线程设置的值

内存泄露

static class threadlocalmap {

	static class entry extends weakreference<threadlocal<?>> {
		object value;

		entry(threadlocal<?> k, object v) {
			super(k);
			value = v;
		}
	}
}

threadlocalmap使用threadlocal的弱引用作为key,如果一个threadlocal没有外部强引用来引用它,那么系统 gc 的时候,这个threadlocal势必会被回收,这样一来,threadlocalmap中就会出现key为null的entry,就没有办法访问这些key为null的entry的value,如果当前线程再迟迟不结束的话,这些key为null的entry的value就会一直存在一条强引用链:thread ref -> thread -> threalocalmap -> entry -> value永远无法回收,造成内存泄漏

大白话一点,threadlocalmap的key是弱引用,gc时会被回收掉,那么就有可能存在threadlocalmap<null, object>的情况,这个object就是泄露的对象

其实,threadlocalmap的设计中已经考虑到这种情况,也加上了一些防护措施:在threadlocal的get(),set(),remove()的时候都会清除线程threadlocalmap里所有key为null的value

解决办法

解决以上两个问题的办法很简单,就是在每次用完threadlocal后,及时调用remove()方法清理即可

欢迎关注

在这里插入图片描述

参考博客

神奇的threadlocal
[1]https://mp.weixin.qq.com/s/kutspyfmkdk4ajletifujg
还在使用simpledateformat?你的项目崩没?
threadlocal为什么会内存泄漏
[2]https://blog.xiaohansong.com/threadlocal-memory-leak.html
[3]

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网