views:

137

answers:

7

Everybody cautions regarding Java DateFormat not being thread safe and I understand the concept theoretically.

But I'm not able to visualize what actual issues we can face due to this - say, I've a DateFormat field in class and the same is used in different methods in the class(formatting dates) in a multi-threaded environment. Will this cause: - any exception like format exception - discrepancy in data - anything other issue?

Also, plz explain why.

+2  A: 

Roughly, that you should not define a DateFormat as instance variable of an object accessed by many threads, or static.

Date formats are not synchronized. It is recommended to create separate format instances for each thread.

So, in case your Foo.handleBar(..) is accessed by multiple threads, instead of:

public class Foo {
    private DateFormat df = new SimpleDateFormat("dd/mm/yyyy");

    public void handleBar(Bar bar) {
        bar.setFormattedDate(df.format(bar.getStringDate());  
    }
}

you should use:

public class Foo {

    public void handleBar(Bar bar) {
        DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
        bar.setFormattedDate(df.format(bar.getStringDate());  
    }
}

Also, in all cases, don't have a static DateFormat

As noted by Jon Skeet, you can have both static and a shared instance variables in case you perform external synchronization (i.e. use synchronized around calls to the DateFormat)

Bozho
I don't see that that follows at all. I don't make most of my types thread-safe, so I don't expect their instance variables to be thread-safe either, necessarily. It's more reasonable to say that you shouldn't store a DateFormat in a *static* variable - or if you do, you'll need synchronization.
Jon Skeet
@Jon Skeet I clarified.
Bozho
@Bozho: That's generally better - although it would be okay to have a static DateFormat if you *did* synchronize. That may well perform better in many cases than creating a new `SimpleDateFormat` very frequently. It will depend on the usage pattern.
Jon Skeet
+2  A: 

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

This means suppose you have a object of DateFormat and you are accessing same object from two different threads and you are calling format method upon that object both thread will enter on the same method at the same time on the same object so you can visualize it won't result in proper result

If you have to work with DateFormat any how then you should do something

public synchronized myFormat(){
// call here actual format method
}
org.life.java
A: 

If there are multiple threads manipulating/accessing a single DateFormat instance and synchronization not used, it's possible to get scrambled results. That's because multiple non-atomic operations could be changing state or seeing memory inconsistently.

seand
+8  A: 

I would expect data corruption - e.g. if you're parsing two dates at the same time, you could have one call polluted by data from another.

It's easy to imagine how this could happen: parsing often involves maintaining a certain amount of state as to what you've read so far. If two threads are both trampling on the same state, you'll get problems. For example, DateFormat exposes a calendar field of type Calendar, and looking at the code of SimpleDateFormat, some methods call calendar.set(...) and others call calendar.get(...). This is clearly not thread-safe.

I haven't looked into the exact details of why DateFormat isn't thread-safe, but for me it's enough to know that it is unsafe without synchronization - the exact manners of non-safety could even change between releases.

Personally I would use the parsers from Joda Time instead, as they are thread safe - and Joda Time is a much better date and time API to start with :)

Jon Skeet
+1 for recommending JodaTime.
Faisal Feroz
+1  A: 

Data is corrupted. Yesterday I noticed it in my multithread program where I had static DateFormat object and called its format() for values read via JDBC. I had SQL select statement where I read the same date with different names (SELECT date_from, date_from AS date_from1 ...). Such statements were using in 5 threads for various dates in WHERE clasue. Dates looked "normal" but they differed in value -- while all dates were from the same year only month and day changed.

Others answers show you the way to avoid such corruption. I made my DateFormat not static, now it is a member of a class that calls SQL statements. I tested also static version with synchronizing. Both worked well with no difference in performance.

Michał Niklas
A: 

The specifications of Format, NumberFormat, DateFormat, MessageFormat, etc. were not designed to be thread-safe. Also, the parse method calls on Calendar.clone() method and it affects calendar footprints so many threads parsing concurrently will change the cloning of the Calendar instance.

For more, these are bug reports such as this and this, with results of DateFormat thread-safety issue.

The Elite Gentleman
+3  A: 

Let's try it out.

Here is a program in which multiple threads use a shared SimpleDateFormat.

Program:

public static void main(String[] args) throws Exception {

    final DateFormat format =
        new SimpleDateFormat("yyyyMMdd");

    Callable<Date> task = new Callable<Date>(){
        public Date call() throws Exception {
            return format.parse("20101022");
        }
    };

    //pool with 5 threads
    ExecutorService exec = Executors.newFixedThreadPool(5);
    List<Future<Date>> results =
                 new ArrayList<Future<Date>>();

    //perform 10 date conversions
    for(int i = 0 ; i < 10 ; i++){
        results.add(exec.submit(task));
    }
    exec.shutdown();

    //look at the results
    for(Future<Date> result : results){
        System.out.println(result.get());
    }
}

Run this a few times and you will see:

Exceptions:

Here are a few examples:

1.

Caused by: java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Long.parseLong(Long.java:431)
    at java.lang.Long.parseLong(Long.java:468)
    at java.text.DigitList.getLong(DigitList.java:177)
    at java.text.DecimalFormat.parse(DecimalFormat.java:1298)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1589)

2.

Caused by: java.lang.NumberFormatException: For input string: ".10201E.102014E4"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
    at java.lang.Double.parseDouble(Double.java:510)
    at java.text.DigitList.getDouble(DigitList.java:151)
    at java.text.DecimalFormat.parse(DecimalFormat.java:1303)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1589)

3.

Caused by: java.lang.NumberFormatException: multiple points
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1084)
    at java.lang.Double.parseDouble(Double.java:510)
    at java.text.DigitList.getDouble(DigitList.java:151)
    at java.text.DecimalFormat.parse(DecimalFormat.java:1303)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1936)
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1312)

Incorrect Results:

Sat Oct 22 00:00:00 BST 2011
Thu Jan 22 00:00:00 GMT 1970
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Thu Oct 22 00:00:00 GMT 1970
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010

Correct Results:

Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010
Fri Oct 22 00:00:00 BST 2010

Another approach to safely use DateFormats in a multi-threaded environment is to use a ThreadLocal variable to hold the DateFormat object, which means that each thread will have its own copy and doesn't need to wait for other threads to release it. This is how:

public class DateFormatTest {

  private static final ThreadLocal<DateFormat> df
                 = new ThreadLocal<DateFormat>(){
    @Override
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyyMMdd");
    }
  };

  public Date convert(String source)
                     throws ParseException{
    Date d = df.get().parse(source);
    return d;
  }
}

Here is a good post with more details.

dogbane