JAVA高并发获取到的系统时间异常,SimpleDateFormat的线程安全问题

当前在做一个大型的物联网的采集系统,建立多个采集任务对网关进行采集,采集任务均调用同一个方法对采集到的数据进行处理。偶然出现部分数据时间异常,和当前时间相差非常大。几千条数据出现三条时间异常,第四条为当前时间,如下:
在这里插入图片描述
Java代码

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 sdf.format(new Date());

查阅代码逻辑并无问题,于是推断为获取到的时间有问题,想起SimpleDateFormat不是线程安全的,单线程下不会出现问题,但是高并发时便会出现问题。遂对方法进行封装:

  private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();

    public static String formatDate(Date date) throws ParseException {
        return getFormat().format(date);
    }

    public static Date parseDate(String strDate) throws ParseException {
        return getFormat().parse(strDate);
    }

    public static DateFormat getFormat(){
        DateFormat dateFormat = threadLocal.get();
        if(dateFormat==null){
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            threadLocal.set(dateFormat);
        }
        return dateFormat;
    }

问题解决!

发布了34 篇原创文章 · 获赞 1 · 访问量 536

猜你喜欢

转载自blog.csdn.net/weixin_42440154/article/details/95100820
今日推荐