Java – Strange ArrayIndexOutOfBoundsException for Java SimpleDateFormat

indexoutofboundsexceptionjavasimpledateformat

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?

Best Answer

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.