4

我需要在bean中使用DateFormat对象。jxls如果在我的课堂上我写以下内容:

private synchronized DateFormat df = new SimpleDateFormat("dd.MM.yyyy");

它会是线程安全的吗?在同一个类中,我有一个方法:

public void doSomething() {
    Map<String,String> beans = new HashMap<String,String>();
    beans.put("df",df);
    XLSTransformer transformer = new XLSTransformer();
    transformer.transformXLS("template.xls", beans, "result.xls");
}

这是从多个线程调用的。

如果synchronized字段在这种情况下没有帮助,我可以做些什么来提供线程安全的日期格式,而无需每次都jxls创建新对象?DateFormat

4

1 回答 1

2

不,您不能添加synchronized到这样的字段中。

  1. 您可以在每次调用时创建一个doSomething

例如:

public void doSomething() {
    Map<String,String> beans = new HashMap<String,String>();
    beans.put("df", new SimpleDateFormat("dd.MM.yyyy"));
    XLSTransformer transformer = new XLSTransformer();
    transformer.transformXLS("template.xls", beans, "result.xls");
}

由于每个调用线程都会获得自己的 this 实例,SimpleDateFormat因此这将是线程安全的(假设 SimpleDateFormat 不会存在很长时间,并且在传递给 xslt 转换器时会传递给其他线程)。

  1. 创建一个ThreadLocal来处理多个线程:

例如:

private static final ThreadLocal<SimpleDateFormat> df =
    new ThreadLocal<Integer>() {
         @Override protected Integer initialValue() {
             return new SimpleDateFormat("dd.MM.yyyy");
     }
 };
 public void doSomething() {
    // ...
    beans.put("df", df.get());
    // ...
}
  1. 另一种选择是更改您的代码以使用 jodatime DateTimeFormat。DateTimeFormat 类是线程安全的。
于 2015-04-19T05:55:44.877 回答