我Converter
在 JSF 1.2 中创建了一个自定义来转换Date
对象。日期具有非常特殊的格式。我已经使用核心 JavaSimpleDateFormat
类实现了我的转换器,使用下面我的代码注释中显示的格式化程序字符串进行转换。这一切都很好。
我的问题是关于线程安全的。SimpleDateFormat
API 文档声明它不是线程安全的。出于这个原因,我为转换器对象的每个实例创建了一个单独的日期格式对象实例。但是,我不确定这是否足够。我的DateFormat
对象存储为DTGDateConverter
.
问题:两个线程会同时访问JSF 中的Converter 对象的同一个实例吗?
如果答案是肯定的,那么我的转换器可能处于危险之中。
/**
* <p>JSF Converter used to convert from java.util.Date to a string.
* The SimpleDateFormat format used is: ddHHmm'Z'MMMyy.</p>
*
* <p>Example: October 31st 2010 at 23:59 formats to 312359ZOCT10</p>
*
* @author JTOUGH
*/
public class DTGDateConverter implements Converter {
private static final Logger logger =
LoggerFactory.getLogger(DTGDateConverter.class);
private static final String EMPTY_STRING = "";
private static final DateFormat DTG_DATE_FORMAT =
MyFormatterUtilities.createDTGInstance();
// The 'format' family of core Java classes are NOT thread-safe.
// Each instance of this class needs its own DateFormat object or
// runs the risk of two request threads accessing it at the same time.
private final DateFormat df = (DateFormat)DTG_DATE_FORMAT.clone();
@Override
public Object getAsObject(
FacesContext context,
UIComponent component,
String stringValue)
throws ConverterException {
Date date = null;
// Prevent ParseException when an empty form field is submitted
// for conversion
if (stringValue == null || stringValue.equals(EMPTY_STRING)) {
date = null;
} else {
try {
date = df.parse(stringValue);
} catch (ParseException e) {
if (logger.isDebugEnabled()) {
logger.debug("Unable to convert string to Date object", e);
}
date = null;
}
}
return date;
}
@Override
public String getAsString(
FacesContext context,
UIComponent component,
Object objectValue)
throws ConverterException {
if (objectValue == null) {
return null;
} else if (!(objectValue instanceof Date)) {
throw new IllegalArgumentException(
"objectValue is not a Date object");
} else {
// Use 'toUpperCase()' to fix mixed case string returned
// from 'MMM' portion of date format
return df.format(objectValue).toUpperCase();
}
}
}