用struts2时,许多时候都会用到自定义的日期转换类。网上有许多现成的代码,拿过来基本可以使用。
public class DateConverter extends StrutsTypeConverter {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Override
@SuppressWarnings("rawtypes")
public Object convertFromString(Map context, String[] values, Class toClass) {
Date date = null;
try {
date = sdf.parse(values[0]);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
@Override
@SuppressWarnings("rawtypes")
public String convertToString(Map context, Object o) {
Date d =(Date)o;
String date = sdf.format(d);
return date;
}
}
这些代码基本都是把SimpleDateFormat的实例做为一个类成员,当并发量变大时,可能会导致某些日期转换不正确。通过查看SimpleDateFormat的代码可以看到这样的类注释:
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.
接下来怎么就不用说了。
1. 每次new一个对象
2. 用threadlocal对象存储,为每个线程创建一个实例