我需要在DateFormat bean中使用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字段在这种情况下没有帮助,那么在每次创建新的DateFormat对象的情况下,如何从jxls提供线程安全的数据格式设置呢?
发布于 2015-04-19 05:55:44
不,不能将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实例,这将是threadsafe (假设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());
// ...
}DateTimeFormat。DateTimeFormat类是线程安全的。https://stackoverflow.com/questions/29726320
复制相似问题