問題
在多線程中,如果采用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>