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?
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.
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With