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

16 浏览
0 Comments

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

以上行内容出现在 SimpleDateFormat 类的 JavaDoc 中。

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

如果我们将其创建为静态的,则无论我们在何处使用此对象,都需要将其放置在同步块中。

admin 更改状态以发布 2023年5月23日
0
0 Comments

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

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

0
0 Comments

这是真的。你可以在StackOverflow上找到关于这个问题的已有问题。我通常将其声明为ThreadLocal

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

在代码中:

DateFormat df = THREAD_LOCAL_DATEFORMAT.get();

0