问题
在多线程中,如果采用SimpleDateFormat直接进行日期转化需要注意,有坑,SimpleDateFormat的parser等方法非线程安全,有两个办法解决,一个通过线程本地变量。
当然如果你每次都new一个SimpleDateFormat对象没问题,不过这样比较耗性能。
解决办法
1.通过线程的本地变量解决
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
public static DateFormat IndexDayModeFormat()
{
DateFormat df = threadLocal.get();
if(df==null){
df = new SimpleDateFormat("yyyyMMdd");
threadLocal.set(df);
}
return df;
}
collectionDate = IndexDayModeFormat().parse(dateTime);
2.使用FastDateFormat
dirDateFormat = FastDateFormat.getInstance("yyyyMMdd");
其他用法类似,需要引入的jar
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>