Strange ArrayIndexOutOfBoundsException for Java SimpleDateFormat

坚强是说给别人听的谎言 提交于 2019-12-04 00:51:40

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.

Looks like this bug report. The underlying reason was diagnosed to be that DecimalFormat simply isn't thread safe.

So you should not use the same SimpleDateFormat instance on different threads, since it, and DecimalFormat still aren't thread safe.

You could use ThreadLocal to have each thread use its own instance.

A simple way to create instance each time, a local/scope variable instead of global variable, it works for me

private void test {
    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(pattern, Locale.ENGLISH);
    // Do somethings
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!