[英]java.text.SimpleDateFormat not thread safe
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对象创建为Static。
And If we create it as static, so wherever we are using this object we need to keep it in Synchronised Block. 如果我们将它创建为静态,那么无论我们在哪里使用这个对象,我们都需要将它保存在Synchronized Block中。
That's true. 确实如此。 You can find already questions concerning this issue on StackOverflow. 您可以在StackOverflow上找到有关此问题的问题。 I use to declare it as ThreadLocal
: 我用它来声明它为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();
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
Thats correct. 多数民众赞成。 FastDateFormat from 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之前只进行格式化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.