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