首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >同步DateFormat - jxls

同步DateFormat - jxls
EN

Stack Overflow用户
提问于 2015-04-19 05:52:55
回答 1查看 1.1K关注 0票数 4

我需要在DateFormat bean中使用jxls对象。如果在我的课堂上,我写了以下几点:

代码语言:javascript
复制
private synchronized DateFormat df = new SimpleDateFormat("dd.MM.yyyy");

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

代码语言:javascript
复制
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字段在这种情况下没有帮助,那么在每次创建新的DateFormat对象的情况下,如何从jxls提供线程安全的数据格式设置呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-19 05:55:44

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

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

例如:

代码语言:javascript
复制
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");
}

因为每个调用线程都将获得自己的SimpleDateFormat实例,这将是threadsafe (假设SimpleDateFormat活不长,并在传递到XSLT转换器时传递给其他线程)。

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

例如:

代码语言:javascript
复制
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类是线程安全的。
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29726320

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档