Java SimpleDateFormat的奇怪ArrayIndexOutOfBoundsException [英] Strange ArrayIndexOutOfBoundsException for Java SimpleDateFormat

查看:535
本文介绍了Java SimpleDateFormat的奇怪ArrayIndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们运行Java 1.4.

We run 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.这一直在起作用,但是突然停止了!

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

我们现在得到此异常:

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不是线程安全的

不是 个bug: javadoc 记录了这种行为:

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.

这篇关于Java SimpleDateFormat的奇怪ArrayIndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆