我需要在 jxls
bean 中使用 DateFormat
对象。如果在我的类里面我写了以下内容:
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
对象每次?
最佳答案
不,你不能将 synchronized
添加到这样的字段。
- 您可以在每次调用
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");
}
由于每个调用线程都将获得自己的 SimpleDateFormat
实例,这将是线程安全的(假设 SimpleDateFormat 生命周期不长并且在传递给 xslt 转换器时传递给其他线程) .
- 创建一个
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());
// ...
}
- 另一种选择是更改您的代码以使用 jodatime
DateTimeFormat
反而。 DateTimeFormat 类是线程安全的。
关于Java - 同步日期格式 - jxls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29726320/