Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

Everybody cautions regarding Java DateFormat not being thread safe and I understand the concept theoretically.

But I'm not able to visualize what actual issues we can face due to this. Say, I've a DateFormat field in a class and the same is used in different methods in the class (formatting dates) in a multi-threaded environment.

Will this cause:

  • any exception like format exception
  • discrepancy in data
  • any other issue?

Also, please explain why.

1 Answer

0 votes
by (46k points)

I would expect data corruption - e.g. if you're parsing two dates at the same time, you could have one call polluted by data from another.

It's easy to imagine how this could happen: parsing often involves maintaining a certain amount of state as to what you've read so far. If two threads are both trampling on the same state, you'll get problems. For example, DateFormat exposes a calendar field of type Calendar, and looking at the code of SimpleDateFormat, some methods call calendar.set(...) and others call calendar.get(...). This is clearly not thread-safe.

I haven't looked into the exact details of why DateFormat isn't thread-safe, but for me it's enough to know that it is unsafe without synchronization - the exact manners of non-safety could even change between releases.

Personally I would use the parsers from Joda Time instead, as they are thread safe - and Joda Time is a much better date and time API to start with :)

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 22, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 26, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...