SimpleDateFormat and concurrency – a trap

Initial situation: A part of a project I’ve worked on was a multi-threaded log file analyzer. To get the date of each log entry I used SimpleDateFormat.

Not exactly reading the javadoc I defined the SimpleDataFormat like this:
static final SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
If just one thread was used, it works as expected. But if more than one thread was used, the analyzed date didn’t match the date of the log entry.

It took hours to find out that SimpleDateFormat isn’t thread-save. Waste of time because the javadoc contains the right hint.

Ok, there are two options to solve this problem:

  1. Surround a synchronized block where to access SimpleDateFormat or
  2. create a new instance of SimpleDateFormat for each thread.

After profiling the application with both solutions we decided on 2. Option 1 caused too many locks with increasing number of threads. But if the memory usage is important, you should use option 1.

Hint: Same is true for NumberFormat and inherited classes!

, ,

  1. #1 by Mark on 2012/07/13 - 13:53

    use ThreadLocal

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: