文章目录
- 不可变类
- SimpleDateFormat
- 为什么不安全?
- 解决
- 不可变类保证线程安全的实现
不可变类
SimpleDateFormat
public static void main(String[] args) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");for (int i = 0; i < 100; i++) {new Thread(() -> {try {System.out.println(simpleDateFormat.parse("1951-04-21"));} catch (ParseException e) {e.printStackTrace();}}).start();}}
SimpleDateFormat是一个线程不安全的,多线程下大概率出现报错:
为什么不安全?
来看看这个方法:
@Overridepublic Date parse(String text, ParsePosition pos){checkNegativeNumberExpression();int start = pos.index;int oldStart = start;int textLength = text.length();boolean[] ambiguousYear = {false};CalendarBuilder calb = new CalendarBuilder();for (int i = 0; i < compiledPattern.length; ) {int tag = compiledPattern[i] >>> 8;int count = compiledPattern[i++] & 0xff;if (count == 255) {count = compiledPattern[i++] << 16;count |= compiledPattern[i++];}switch (tag) {case TAG_QUOTE_ASCII_CHAR:if (start >= textLength || text.charAt(start) != (char)count) {pos.index = oldStart;pos.errorIndex = start;return null;}start++;break;case TAG_QUOTE_CHARS:while (count-- > 0) {if (start >= textLength || text.charAt(start) != compiledPattern[i++]) {pos.index = oldStart;pos.errorIndex = start;return null;}start++;}break;default:// Peek the next pattern to determine if we need to// obey the number of pattern letters for// parsing. It's required when parsing contiguous// digit text (e.g., "20010704") with a pattern which// has no delimiters between fields, like "yyyyMMdd".boolean obeyCount = false;// In Arabic, a minus sign for a negative number is put after// the number. Even in another locale, a minus sign can be// put after a number using DateFormat.setNumberFormat().// If both the minus sign and the field-delimiter are '-',// subParse() needs to determine whether a '-' after a number// in the given text is a delimiter or is a minus sign for the// preceding number. We give subParse() a clue based on the// information in compiledPattern.boolean useFollowingMinusSignAsDelimiter = false;if (i < compiledPattern.length) {int nextTag = compiledPattern[i] >>> 8;if (!(nextTag == TAG_QUOTE_ASCII_CHAR ||nextTag == TAG_QUOTE_CHARS)) {obeyCount = true;}if (hasFollowingMinusSign &&(nextTag == TAG_QUOTE_ASCII_CHAR ||nextTag == TAG_QUOTE_CHARS)) {int c;if (nextTag == TAG_QUOTE_ASCII_CHAR) {c = compiledPattern[i] & 0xff;} else {c = compiledPattern[i+1];}if (c == minusSign) {useFollowingMinusSignAsDelimiter = true;}}}start = subParse(text, start, tag, count, obeyCount,ambiguousYear, pos,useFollowingMinusSignAsDelimiter, calb);if (start < 0) {pos.index = oldStart;return null;}}}// At this point the fields of Calendar have been set. Calendar// will fill in default values for missing fields when the time// is computed.pos.index = start;Date parsedDate;try {parsedDate = calb.establish(calendar).getTime();// If the year value is ambiguous,// then the two-digit year == the default start yearif (ambiguousYear[0]) {if (parsedDate.before(defaultCenturyStart)) {parsedDate = calb.addYear(100).establish(calendar).getTime();}}}// An IllegalArgumentException will be thrown by Calendar.getTime()// if any fields are out of range, e.g., MONTH == 17.catch (IllegalArgumentException e) {pos.errorIndex = start;pos.index = oldStart;return null;}return parsedDate;}
主要是这里调用了establish()
Calendar establish(Calendar cal) {boolean weekDate = isSet(WEEK_YEAR)&& field[WEEK_YEAR] > field[YEAR];if (weekDate && !cal.isWeekDateSupported()) {// Use YEAR insteadif (!isSet(YEAR)) {set(YEAR, field[MAX_FIELD + WEEK_YEAR]);}weekDate = false;}cal.clear();// Set the fields from the min stamp to the max stamp so that// the field resolution works in the Calendar.for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {for (int index = 0; index <= maxFieldIndex; index++) {if (field[index] == stamp) {cal.set(index, field[MAX_FIELD + index]);break;}}}if (weekDate) {int weekOfYear = isSet(WEEK_OF_YEAR) ? field[MAX_FIELD + WEEK_OF_YEAR] : 1;int dayOfWeek = isSet(DAY_OF_WEEK) ?field[MAX_FIELD + DAY_OF_WEEK] : cal.getFirstDayOfWeek();if (!isValidDayOfWeek(dayOfWeek) && cal.isLenient()) {if (dayOfWeek >= 8) {dayOfWeek--;weekOfYear += dayOfWeek / 7;dayOfWeek = (dayOfWeek % 7) + 1;} else {while (dayOfWeek <= 0) {dayOfWeek += 7;weekOfYear--;}}dayOfWeek = toCalendarDayOfWeek(dayOfWeek);}cal.setWeekDate(field[MAX_FIELD + WEEK_YEAR], weekOfYear, dayOfWeek);}return cal;}
参数为calender,那么这个canlender出自哪里呢?
实际上是继承DateFormat里的。
establish中先进行了cal.clear(),又进行了cal.set()。 先清除cal对象中是值,再设置新的值。
这样多线程下,调用同一个cal,而cal又没有设置线程安全,比如线程t1刚set完,t2进行了clear,那t1的输出肯定是不对的。
下面介绍几种解决方法。
解决
方法一:
首先想到的肯定是加锁
public class test10 {public static void main(String[] args) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");for (int i = 0; i < 100; i++) {new Thread(() -> {synchronized (simpleDateFormat) {try {System.out.println(simpleDateFormat.parse("1951-04-21"));} catch (ParseException e) {e.printStackTrace();}}}).start();}}
}
这样可以解决,但是效率肯定是不高的。
方法二:
利用不可变类型DateTimeFormatter
源码介绍是一个不可变的、线程安全的类
public class test10 {public static void main(String[] args) {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");for (int i = 0; i < 100; i++) {new Thread(() -> {TemporalAccessor parse = dateTimeFormatter.parse("1951-04-21");System.out.println(parse);}).start();}}
}
不可变类保证线程安全的实现
不可变类的类,属性都是final修饰的。
例如String:
保证只读和防止修改。
同时其方法都是操作一个新对象,并不在原对象上操作,保证了安全。
之前String都介绍过,这里就不再给出了,可以自己看看String的方法源码。
参考:
https://zhuanlan.zhihu.com/p/395751163