オブジェクトConverter
を変換するために JSF 1.2 でカスタムを作成しました。Date
日付には非常に特殊な形式があります。SimpleDateFormat
以下のコード コメントに示されているフォーマッタ文字列を使用して、コア Java クラスを使用して変換を行うコンバータを実装しました。これはすべてうまくいきます。
私の質問は、スレッドセーフについてです。SimpleDateFormat
API ドキュメントには、スレッドセーフではないと記載されています。そのため、コンバーター オブジェクトのインスタンスごとに、日付形式オブジェクトの個別のインスタンスを作成しました。ただし、これで十分かどうかはわかりません。私のDateFormat
オブジェクトはのメンバーとして保存されますDTGDateConverter
。
質問: 2 つのスレッドはそれぞれ、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();
}
}
}