Java - synchronized DateFormat - jxls

I need to use an object DateFormatin jxlsbeans. If in my class I write the following:

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

Will it be thread safe? In the same class, I have a method:

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");
}

This is called from multiple threads.

If the field is not supported in this situation synchronized, what can I do to ensure that the date is formatted safely jxlswithout creating a new object DateFormateach time?

+4
source share
1 answer

No, you cannot add synchronizedto such fields.

  • You can create it every time you call 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).

  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 .
+2

All Articles