class MyFormatter {
private static SimpleDateFormat sdf = new SimpleDateFormat(
public static String formatDate(Date inputDate) {
return sdf.format(inputDate);
}
}
My reasons for using such an approach was to prevent multiple creation of expensive SimpleDateFormat objects. However, few days back I came across a post that said that the above implementation is thread un-safe. At first I was taken by surprise, and couldn't find a reason for this being un-safe, as the format operation is happening on the local variable (stored on stack).
Then I thought of opening the Java Source Code and understanding the reasons behind this being thread un-safe. The culprit was a class level variable of type Calendar, which is used by the SimpleDateFormat class. Whenever a call to format is invoked, the input date passed is set into this calender object, and then all the operations are performed on this calendar object.
So, if there are 2 threads that are sharing the same SDF object and are running concurrently, the operations will NOT be thread safe and unexpected results can occur.
To resolve this problem, one of the way can be to create a new SDF object everytime in the formatDate method. See below:
class MyFormatter {
public static String formatDate(Date inputDate) {
SimpleDateFormat sdf = new SimpleDateFormat(
return sdf.format(inputDate);
}
}
This will result into the expensive SDF object to be created on every invocation of the formatDate method, however, this is completely thread safe. The even better answer is to use the thread-safe Joda time libraries, instead.
Hoping this helps others as well!!
No comments:
Post a Comment