Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange ArrayIndexOutOfBoundsException for Java SimpleDateFormat

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?

like image 653
lulu88 Avatar asked Aug 22 '13 14:08

lulu88


People also ask

How do I fix Java Lang ArrayIndexOutOfBoundsException in Java?

Here are few handy tips to avoid ArrayIndexOutOfBoundsException in Java: Always remember that the array is a zero-based index, the first element is at the 0th index and the last element is at length - 1 index. Pay special attention to the start and end conditions of the loop. Beware of one-off errors like above.

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.

Is SimpleDateFormat deprecated?

Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.

What causes Java Lang ArrayIndexOutOfBoundsException?

The ArrayIndexOutOfBoundsException is one of the most common errors in Java. It occurs when a program attempts to access an invalid index in an array i.e. an index that is less than 0, or equal to or greater than the length of the array.


1 Answers

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.

like image 189
Bohemian Avatar answered Nov 15 '22 14:11

Bohemian