Posts Tagged concurrency
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:
- Surround a synchronized block where to access SimpleDateFormat or
- 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!