Java中SimpleDateFormate是线程不安全的又会怎么样

这就要分析下SimpleDateFormate为什么是线程不安全的了.看SimpleDataFormat 源码时,会发现提到说SimpleDataFormat不是线程安全的。
* 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.这是因为里面用了Calendar 这个成员变量来实现SimpleDataFormat,并且在Parse 和Format的时候对Calendar 进行了修改,calendar.clear(),calendar.setTime(date);
观察下面的parse方法
public Date parse(String text, ParsePosition pos){ int start = pos.index; int oldStart = start; int textLength = text.length(); calendar.clear(); // Clears all the time fields boolean ambiguousYear = {false}; for (int i = 0; i \u0026lt; compiledPattern.length; ) { int tag = compiledPattern \u0026gt;\u0026gt;\u0026gt; 8; int count = compiledPattern \u0026amp; 0xff; if (count == 255) { count = compiledPattern \u0026lt;\u0026lt; 16; count |= compiledPattern; } switch (tag) { case TAG_QUOTE_ASCII_CHAR: if (start \u0026gt;= textLength || text.charAt(start) != (char)count) { pos.index = oldStart; pos.errorIndex = start; return null; } start++; break; case TAG_QUOTE_CHARS: while (count-- \u0026gt; 0) { if (start \u0026gt;= textLength || text.charAt(start) != compiledPattern) { pos.index = oldStart; pos.errorIndex = start; return null; } start++; } break; default: boolean obeyCount = false; if (i \u0026lt; compiledPattern.length) { int nextTag = compiledPattern \u0026gt;\u0026gt;\u0026gt; 8; if (!(nextTag == TAG_QUOTE_ASCII_CHAR || nextTag == TAG_QUOTE_CHARS)) { obeyCount = true; } } start = subParse(text, start, tag, count, obeyCount, ambiguousYear, pos); if (start \u0026lt; 0) { pos.index = oldStart; return null; } } } pos.index = start; Date parsedDate; try { if (ambiguousYear) // If this is true then the two-digit year == the default start year { Calendar savedCalendar = (Calendar)calendar.clone(); parsedDate = calendar.getTime(); if (parsedDate.before(defaultCenturyStart)) { // We can\u0026#39;t use add here because that does a complete() first. savedCalendar.set(Calendar.YEAR, defaultCenturyStartYear + 100); parsedDate = savedCalendar.getTime(); } } else parsedDate = calendar.getTime(); } catch (IllegalArgumentException e) { pos.errorIndex = start; pos.index = oldStart; return null; } return parsedDate; }


推荐阅读