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; }
推荐阅读
- dart这编程语言现在发展怎么样了,语法与Java,c#很相似,甚至更简洁
- Java工程师和C++工程师在工作上有啥区别哪个更适合自身发展
- 27岁,转行java的血与泪,该何去何从
- 怎样统计工程中未使用的java类
- 新互联网网站用Java还靠谱么对比Php,Python,Ruby的话
- 我想学java和安卓软件开发?
- 学计算机专业,java那些和网站开发选台式还是笔记本好
- JAVA设计思路
- 本人大专毕业一年,想要去培训,定了JAVAEE和安卓两个方向,应该学那个纠结,求帮助
- 从未接触过软件测试和java,可以学习主要是自学这两种其一吗
