java获取线程安全的流水号_JAVA高并发获取到的系统时间异常,SimpleDateFormat的线程安全问题...

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

47efa718836c035ad9e32516647e0efa.png

Java代码

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

sdf.format(new Date());

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

private static ThreadLocal threadLocal = new ThreadLocal();

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;

}

问题解决!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值