SimpleDateFormat is NOT immutable

Yes, SimpleDateFormat is not immutable as name may suggest. This came as complete surprise to me. When using from multiple threads then appeared exceptions like:

 java.lang.NumberFormatException: For input string: ""
 at java.lang.NumberFormatException.forInputString
(NumberFormatException.java:65)
 at java.lang.Long.parseLong(Long.java:601)
 at java.lang.Long.parseLong(Long.java:631)
 at java.text.DigitList.getLong(DigitList.java:195)
 at java.text.DecimalFormat.parse(DecimalFormat.java:2051)
 at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2162)
 at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
 at java.text.DateFormat.parse(DateFormat.java:364)

Quick check with documentation brought suspicion:

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.

Yes, it was enough to create per-thread SimpleDateFormat.

I think SimpleDateFormat is lousy name and also SimpleDateFormat breaks single responsibility principle. Much better would be decomposition into multiple classes:

  • SimpleDateFormat – immutable object only holding format of date
  • SimpleDateFormatter – mutable object used for formatting according to passed SimpleDateFormat
  • SimpleDataParser – mutable object used for parsing according to passed SimpleDateForma
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s