Thread-safe java.text.SimpleDateFormat format and parse
forax at univ-mlv.fr
Wed Jul 1 17:19:37 UTC 2015
I think we should go a step further and deprecate SimpleDateFormat and
it will save time for everyone (once everyone will have migrated ... ).
On 07/01/2015 06:01 PM, Claes Redestad wrote:
> The suggested approaches would have a negative performance
> impact on code which have addressed the thread-safety issues
> (by synchronizing, using ThreadLocal instances or similar), so I see
> no way this could be fixed in a way that would make everyone
> On 2015-07-01 17:39, Ben Evans wrote:
>> Given the other problems with the legacy date and time classes, why
>> spend engineering time tidying this up?
>> Everyone should be migrating to the new date & time support in
>> java.time, so this would just be a distraction.
>> On Sat, Jun 27, 2015 at 8:36 AM, Paul Draper <paulddraper at gmail.com>
>>> While it's often understood that SimpleDateFormat isn't thread safe
>>> its setters, etc. it is frequently incorrectly assumed (despite the
>>> that since format() and parse() do not mutate the object in a
>>> visible way,
>>> they can be called from multiple threads.
>>> The rationale is akin to calling ArrayList#get or HashMap#get from
>>> threads. The entire class is not thread-safe, but you can call that
>>> non-mutating accessor from multiple threads without issue.
>>> The trouble is that SimpleDateFormat has a private Calendar instance
>>> variable, which is mutated during the format() and parse() methods.
>>> This is a very common mistake. There is a project whose entire
>>> purpose is a
>>> thread-safe formatter:
>>> And Apache Commons and Joda Time provide similar classes.
>>> Currently, users of SimpleDateFormat have to synchronize format() and
>>> parse(), or use a separate SimpleDateFormat for every thread.
>>> Or, too commonly, do neither and have a relatively unobvious race
>>> Making format() and parse() calls thread-safe would require either
>>> using a
>>> local Calendar variable -- one instance per call -- or using a
>>> Calendar -- one instance per thread. The former option seems the best.
>>> The change would be fully backwards compatible. I have profiled a
>>> with a local Calendar variable, and measured no difference in the
>>> performance (format and parse are by their nature rather involved
>>> to begin with).
>>> This change would improve the intuitive behavior of SimpleDateFormat
>>> eliminate one of the most common mistakes of JDK users.
More information about the jdk9-dev