java.text.SimpleDateFormat 不是线程安全的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10411944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:56:52  来源:igfitidea点击:

java.text.SimpleDateFormat not thread safe

javathread-safetysimpledateformat

提问by Sunny Gupta

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.

SimpleDateFormat 类的 JavaDoc 中提到了上述行。

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

这是否意味着我们不应该将 SimpleDateFormat 对象创建为静态。

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

如果我们将它创建为静态,那么无论我们在哪里使用这个对象,我们都需要将它保存在同步块中。

回答by Kai

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

这是真的。您可以在 StackOverflow 上找到有关此问题的已有问题。我用来将其声明为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();

回答by Subhrajyoti Majumder

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

是的 SimpleDateFormat 不是线程安全的,当您解析它应该以同步方式访问的日期时,也建议使用它。

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

另一种方式是在http://code.google.com/p/safe-simple-date-format/downloads/list

回答by J?rn Horstmann

Thats correct. FastDateFormatfrom Apache Commons Lang is a nice threadsafe alternative.

那是正确的。来自 Apache Commons Lang 的FastDateFormat是一个不错的线程安全替代方案。

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

从 3.2 版开始,它也支持解析,在 3.2 版之前只支持格式化。