Strange ArrayIndexOutOfBoundsException for Java SimpleDateFormat

We are launching 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 e.g. It works, but it suddenly stopped!

Now we 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 tried to reproduce this in Unit Test using different date formats, for example:

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

But no luck! Any ideas?

+4
source share
3 answers

Little is known that SimpleDateFormat not thread safe !

This is not an error: javadoc documents this behavior:

Date formats are not synchronized. It is recommended that you create separate format instances for each stream. If several threads access the format at the same time, it must be synchronized from the outside.

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


I don’t feel bad: I fell precisely for this "optimization" (for reusing one permanent instance), and, to my surprise, every time you need to create an instance of a new instance.

+21
source

Looks like this error report . The main reason was that DecimalFormat simply not thread safe.

Therefore, you should not use the same instance of SimpleDateFormat for different threads, as it and DecimalFormat are still not thread safe.

You can use ThreadLocal so that each thread uses its own instance.

+4
source

Try using Commons Lang 3.x FastDateParser and FastDateFormat. These classes are thread safe and faster than SimpleDateFormat. They also support the same format / description syntax specifications as SimpleDateFormat.

0
source

Source: https://habr.com/ru/post/1498402/


All Articles