Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety issue with SimpleDateFormat

I got the following piece of code from a programmers test

private String formatDate(Date date)
{
  String result = "";
  //….
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  result = sdf.format(date);
  //…
  return result;
}

with the additional information that several threads are using the method at once. Are there any problems with this?

My answer is that no, it should be fine (assuming that nothing else is going on in the //... parts).

My motivation is that no global or class data structures are used. The date is passed from each tread as a parameter and inside the method only local variables and local objects are being used. Thus, each thread will get and use it's own object instance of the SimpleDateFormat class.

However, this was not the "correct" answer in the test. The "correct" answer is that the class SimpleDateFormat isn't thread safe and that the access to that object therefore needs to be synchronized.

So, am I or the solution correct?

like image 537
tkarls Avatar asked Nov 16 '12 09:11

tkarls


2 Answers

Your answer is correct. SimpleDateFormat isn't thread-safe that's true but each method call will create an own instance so this is ok. If the SimpleDateFormat were an instance variable this wouldn't be thread-safe (as you mentioned).

like image 71
Kai Avatar answered Oct 05 '22 14:10

Kai


SimpleDateFormatter is not a problem - this is a local variable and it can not be accessed from multiple threads because it is not exposed to the outside. The real problem is Date parameter (as @Marko Topolnik already said). This object can be passed to the method and some thread, that can modify it in the middle of your formatDate method execution. You can use long as parameter type to prevent datarace. To convert Date to long use Date.getTime() method and to create Date from long you can use new Date(long) constructor.

like image 21
gkuzmin Avatar answered Oct 05 '22 12:10

gkuzmin