java.text.SimpleDateFormat不是线程安全的 [英] java.text.SimpleDateFormat not thread safe

查看:77
本文介绍了java.text.SimpleDateFormat不是线程安全的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

JavaDoc中提到了上述行SimpleDateFormat类。

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

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

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

如果我们创建它是静态的,所以无论我们在哪里使用这个对象,我们都需要将它保存在Synchronized Block中。

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

推荐答案

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

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;
}

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

这篇关于java.text.SimpleDateFormat不是线程安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆