4

Converter在 JSF 1.2 中创建了一个自定义来转换Date对象。日期具有非常特殊的格式。我已经使用核心 JavaSimpleDateFormat类实现了我的转换器,使用下面我的代码注释中显示的格式化程序字符串进行转换。这一切都很好。

我的问题是关于线程安全的。SimpleDateFormatAPI 文档声明它不是线程安全的。出于这个原因,我为转换器对象的每个实例创建了一个单独的日期格式对象实例。但是,我不确定这是否足够。我的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();
        }
    }

}
4

2 回答 2

7

两个线程会同时访问 JSF 中 Converter 对象的同一个实例吗?

取决于你如何使用转换器。如果你使用

<h:inputWhatever>
    <f:converter converterId="converterId" />
</h:inputWhatever>

然后将为视图中的每个输入元素创建一个新实例,这是线程安全的(除了非常罕见的极端情况,即最终用户在同一会话中的两个浏览器选项卡中具有两个相同的视图并同时在两个视图上发出回发) .

但是,如果您使用

<h:inputWhatever converter="#{applicationBean.converter}" />

那么同一个实例将在整个应用程序的所有视图中共享,因此不是线程安全的。

但是,您每次创建转换器时都在克隆一个静态DataFormat实例。那部分已经不是线程安全的。您可能会冒着克隆实例的风险,而它的内部状态已被更改,因为它已在其他地方使用过。此外,克隆现有实例不一定比创建新实例便宜。

无论您如何使用转换器,我都建议将其声明为 threadlocal(即在方法块内)。如果创建 everytime 的成本DateFormat是一个主要问题(你有没有分析过它?),那么考虑用JodaTime替换它。

于 2010-12-13T16:30:19.360 回答
2

日期格式不同步。建议为每个线程创建单独的格式实例。如果多个线程同时访问一个格式,它必须在外部同步。

是的,这里不是线程安全的。

将其放在方法的本地并为每个线程创建实例

于 2010-12-13T15:51:41.243 回答