9
Synchronization

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

The above line is mentioned in the JavaDoc of SimpleDateFormat class.

Does it mean that we should not create the SimpleDateFormat objects as Static.

And If we create it as static, so wherever we are using this object we need to keep it in Synchronised Block.

Sunny Gupta
  • 6,219
  • 14
  • 47
  • 80
  • 4
    The new `java.time.format.DateTimeFormatter` (from Java 1.8) "is immutable and thread-safe". Give a look at: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html – Linuslabo Jun 01 '16 at 13:04

3 Answers3

24

That's true. You can find already questions concerning this issue on StackOverflow. I use to declare it as ThreadLocal:

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

and in the code:

DateFormat df = THREAD_LOCAL_DATEFORMAT.get();
Kai
  • 36,811
  • 11
  • 87
  • 101
15

Yes SimpleDateFormat is not thread safe and it is also recommended when you are parsing date it should access in synchronized manner.

public Date convertStringToDate(String dateString) throws ParseException {
    Date result;
    synchronized(df) {
        result = df.parse(dateString);
    }
    return result;
}

one other way is on http://code.google.com/p/safe-simple-date-format/downloads/list

Subhrajyoti Majumder
  • 38,572
  • 11
  • 72
  • 100
9

Thats correct. FastDateFormat from Apache Commons Lang is a nice threadsafe alternative.

Since version 3.2 it supports also parsing, before 3.2 only formatting.

Honza Zidek
  • 6,952
  • 4
  • 52
  • 82
Jörn Horstmann
  • 31,936
  • 11
  • 65
  • 111