用于Java SimpleDateFormat的奇怪ArrayIndexOutOfBoundsException(Strange ArrayIndexOutOfBoundsException for

编程入门 行业动态 更新时间:2024-10-13 00:31:34
用于Java SimpleDateFormat的奇怪ArrayIndexOutOfBoundsException(Strange ArrayIndexOutOfBoundsException for Java SimpleDateFormat)

我们运行Java 1.4。

我们有这个方法:

static SimpleDateFormat xmlFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); public static Date fromXml(String xmlDateTime) { ParsePosition pp = new ParsePosition(0); return xmlFormatter.parse(xmlDateTime, pp); }

例如, xmlDateTime = 2013-08-22T16:03:00 。 这一直在工作,但突然停止!

我们现在得到这个例外:

java.lang.ArrayIndexOutOfBoundsException: -1 at java.text.DigitList.fitsIntoLong(DigitList.java:170) at java.text.DecimalFormat.parse(DecimalFormat.java:1064) at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1381) at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1159)

我试图通过使用不同的日期格式在单元测试中重现这一点,即:

2013-08-22T16:03:00 2013-08-22 16:03:00

但没有运气! 有任何想法吗?

We run Java 1.4.

We have this method:

static SimpleDateFormat xmlFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); public static Date fromXml(String xmlDateTime) { ParsePosition pp = new ParsePosition(0); return xmlFormatter.parse(xmlDateTime, pp); }

Where xmlDateTime = 2013-08-22T16:03:00 for example. This has been working, but suddenly stopped!

We now get this exception:

java.lang.ArrayIndexOutOfBoundsException: -1 at java.text.DigitList.fitsIntoLong(DigitList.java:170) at java.text.DecimalFormat.parse(DecimalFormat.java:1064) at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1381) at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1159)

I have tried to reproduce this in a Unit Test by using different date formats, ie:

2013-08-22T16:03:00 2013-08-22 16:03:00

But no luck! Any ideas?

最满意答案

这是一个鲜为人知的事实, SimpleDateFormat 不是线程安全的

不是一个错误: javadoc记录了这种行为:

日期格式不同步。 建议为每个线程创建单独的格式实例。 如果多个线程同时访问一个格式,它必须在外部同步。

每次你需要创建一个实例,或者如果性能是一个真正的问题,你可以尝试使用ThreadLocal为每个需要的线程存储一个实例。


不要感觉不好:我为这个“优化”而倒下了(重用一个常量实例),令我惊讶的是,每次都必须实例化一个新实例。

It is a little known fact that SimpleDateFormat is not threadsafe!

It is not a bug: The javadoc documents this behaviour:

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.

Create an instance every time you need one, or if performance is a real issue, you could try using ThreadLocal to store an instance for each thread that needs one.


Don't feel bad: I fell for exactly this "optimization" (to reuse a single constant instance), and to my amazement, had to instantiate a new instance every time.

更多推荐

本文发布于:2023-08-01 03:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1353922.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:奇怪   SimpleDateFormat   Java   ArrayIndexOutOfBoundsException   Strange

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!