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?
Date, however, is also unsafe and, since it is received from the outside, datarace issues could ensue.SimpleDateFormatis a real hog to use since it is a) thread-unsafe; b) slow to initialize. One must cache a thread-local instance, the most terrible option.SimpleDateFormats design on performance constrain its use cases. That doesn't imply that each and every usage of this class will have performance issues.