Sun*_*pta 8 java thread-safety 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
Run Code Online (Sandbox Code Playgroud)
上面的行在SimpleDateFormat类的JavaDoc中提到.
这是否意味着我们不应该将SimpleDateFormat对象创建为Static.
如果我们将它创建为静态,那么无论我们在哪里使用这个对象,我们都需要将它保存在Synchronized Block中.
Kai*_*Kai 23
确实如此.您可以在StackOverflow上找到有关此问题的问题.我用它来声明ThreadLocal:
private static final ThreadLocal<DateFormat> THREAD_LOCAL_DATEFORMAT = new ThreadLocal<DateFormat>() {
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyyMMdd");
}
};
Run Code Online (Sandbox Code Playgroud)
并在代码中:
DateFormat df = THREAD_LOCAL_DATEFORMAT.get();
Run Code Online (Sandbox Code Playgroud)
Sub*_*der 15
是SimpleDateFormat不是线程安全的,并且在解析它应该以同步方式访问的日期时也建议使用它.
public Date convertStringToDate(String dateString) throws ParseException {
Date result;
synchronized(df) {
result = df.parse(dateString);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是http://code.google.com/p/safe-simple-date-format/downloads/list
| 归档时间: |
|
| 查看次数: |
17938 次 |
| 最近记录: |