DateFormat 多线程问题
在写实时应用解析日志的时候,有如下代码:
1 public class CalPvLogParse { 2 private static SimpleDateFormat logTimeFormat = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss"); 3 4 public static CalPvLog process(PvLog pvLog) { 5 try { 6 String dateStr = DateUtil.getDateStr(logTimeFormat.parse(pvLog.getLogTime())); 7 String hourStr = DateUtil.getHourStr(logTimeFormat.parse(pvLog.getLogTime())); 8 String cookie = pvLog.getCookie(); 9 String displayType = pvLog.getDisplayType(); 10 String kdt_id = pvLog.getKdt_id(); 11 String displayId = pvLog.getDisplayId(); 12 return new CalPvLog(dateStr, hourStr, cookie, displayType, displayId, kdt_id); 13 } 14 catch (ParseException e) { 15 System.err.println("parse CalPvLog error"); 16 return null; 17 } 18 } 19 }
以上代码在写的单元测试中能够顺利通过,但是接线上以后总是出现一些莫名奇怪的错误。报的异常基本在代码6,7行处(由于当时没有截图,所以不能贴了)。查了一下,原因是SimpleDateFormat不是线程安全的。一个简单的解决办法是每次解析时都重新new一个SimpleDateFormat对象,但是资源耗费厉害。后来发现,java有比较成熟的处理日期各种格式转化的joda-time库,接口简单并且是线程安全的,修改如下:
1 public class CalPvLogParse { 2 private static DateTimeFormatter format = DateTimeFormat.forPattern("yyyy/MM/dd-HH:mm:ss"); 3 4 public static CalPvLog process(PvLog pvLog) { 5 DateTime dateTime = DateTime.parse(pvLog.getLogTime(), format); 6 String dateStr = dateTime.toString("MMdd"); 7 String hourStr = dateTime.toString("HH"); 8 String cookie = pvLog.getCookie(); 9 String displayType = pvLog.getDisplayType(); 10 String kdt_id = pvLog.getKdt_id(); 11 String displayId = pvLog.getDisplayId(); 12 return new CalPvLog(dateStr, hourStr, cookie, displayType, displayId, kdt_id); 13 } 14 }
修改以后,问题解决。 另外pom配置如下:
1 <dependency> 2 <groupId>joda-time</groupId> 3 <artifactId>joda-time</artifactId> 4 <version>2.9.4</version> 5 </dependency>