java.text.SimpleDateFormat not thread safe

橙三吉。 提交于 2019-12-18 13:20:57

问题


Synchronization

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

The above line is mentioned in the JavaDoc of SimpleDateFormat class.

Does it mean that we should not create the SimpleDateFormat objects as Static.

And If we create it as static, so wherever we are using this object we need to keep it in Synchronised Block.


回答1:


Yes SimpleDateFormat is not thread safe and it is also recommended when you are parsing date it should access in synchronized manner.

public Date convertStringToDate(String dateString) throws ParseException {
    Date result;
    synchronized(df) {
        result = df.parse(dateString);
    }
    return result;
}

one other way is on http://code.google.com/p/safe-simple-date-format/downloads/list




回答2:


That's true. You can find already questions concerning this issue on StackOverflow. I use to declare it as ThreadLocal:

private static final ThreadLocal<DateFormat> THREAD_LOCAL_DATEFORMAT = new ThreadLocal<DateFormat>() {
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyyMMdd");
    }
};

and in the code:

DateFormat df = THREAD_LOCAL_DATEFORMAT.get();



回答3:


Thats correct. FastDateFormat from Apache Commons Lang is a nice threadsafe alternative.

Since version 3.2 it supports also parsing, before 3.2 only formatting.



来源:https://stackoverflow.com/questions/10411944/java-text-simpledateformat-not-thread-safe

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