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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With