SimpleDateFormat在多线程场景下会出现问题,JDK中类注释也给出了明确说明,:
* Date formats are not synchronized.
* It is recommended to create separate format instances for each thread.
* If multiple threads access a format concurrently, it must be synchronized
* externally.
那么,为什么会这样呢?下面简单分析下基本原理,以parse为例:
@Override
public Date parse(String text, ParsePosition pos)
{
......
Date parsedDate;
try {
parsedDate = calb.establish(calendar).getTime();
// If the year value is ambiguous,
// then the two-digit year == the default start year
if (ambiguousYear[0]) {
if (parsedDate.before(defaultCenturyStart)) {
parsedDate = calb.addYear(100).establish(calendar).getTime();
}